Link 3 tables in an SQL query

Asked

Viewed 88 times

0

I’m in a quasi-deadly doubt I don’t know will it be possible to run with just one query. I have three tables in the bank where they relate to foreign keys so far everything well I am able to relate them. The problem becomes where the Table Images has no or several images linked to a post, only then I want to return the data of the post, with the user who posted and the images if there is, that part of the image that is intriguing me, I want to get only the URLS of the images but instead it duplicates the post and returns me along with the different urls. I am running this query below:

SELECT P.*, U.fistname, U.lastname, U.username, PI.url
FROM posts as P
INNER JOIN user as U ON P.User_id = U.id
LEFT JOIN post_has_image as PI ON PI.Posts_id = P.id
WHERE U.id IN (SELECT User_id1 FROM followers WHERE User_id = 1);

But the result is:

Tabela

I would like the following result:

2 message first2 2 Harry Potter harrypotter url url url(since there are 3 urls in the table image)

3 Massage first3 2 Harry Potter harrypotter null

4 message first4 3 Hermione Granger Hermione null

If the table mount is wrong or there is some way to have this result in a single query, I know that running two queries with you returns but I wonder if there really is a solution to run in just one query.

Thanks in advance.

  • 1

    Whereas the urj field is a string search for the aggregation function GROUP_CONCAT() and use the appropriate GROUP BY clause.

1 answer

0


In this specific case, you can use a sub-select, since it is selecting only one column from the foreign table, which avoids you placing all the other columns in the group by. If you do not want a sub-select, you will have to write the complete query including taking the *

That said, just group several lines in one, in this case using the function GROUP_CONCAT

SELECT 
    P.*, 
    U.fistname, 
    U.lastname, 
    U.username, 
    (Select  GROUP_CONCAT(PI.url) from post_has_image as PI WHERE PI.Posts_id = P.id) as imgs
FROM posts as P
INNER JOIN user as U ON P.User_id = U.id
WHERE U.id IN (SELECT User_id1 FROM followers WHERE User_id = 1);

by default, all URL will be separated by comma, if you want, you can enter another tab.

  • Okay, your query works perfectly. I also applied the other method that you and @anonimo mentioned was not using sub-select but already using cancat and a group by. Both work correctly, exist the most suitable or whatever between them? Already learning more today, did not know that existed this GROUP_CONCAT.

  • I believe that it is not a question of "more appropriate" but rather that it depends on what you are using, in this case, I put as sub-select because it would only be a column of the "foreign" table and avoid the group by.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.