sqlmysqlleft-joinunion

Select data from two records in same table in a single query using MySQL and PHP


I have a MySQL query involving JOINS and Union statements whereby I query multiple tables to produce a JSON feed.

I now have to add comments. If the comment is about something in a separate table such as Articles, then I can JOIN the two tables.

If the comment is on a comment, I need information from two rows of the same table--the new comment row 2 and the original comment row 1 that the new comment is about.

How do I get data from two rows of one table in a single query?

The first left join in my second subquery doesn't work.

Articles id|text|pic|authorid
Users id|name|pic
Comments id|articleid|userid|commentid|text

SELECT a.id as 'itemid', a.text as 'body', a.pic as 'itempic',
    u.name as 'authorname', u.pic as 'authorpic', nil as 'subtext' 
FROM Articles `a`
LEFT JOIN Users `u` 
ON a.authorid = u.id

UNION

SELECT c.id as 'itemid',c.comment as 'body', nil as 'itempic',
    u.name as 'authorname', u.pic as 'authorpic', cm.text as 'subtext' 
FROM COMMENTS `c`
LEFT JOIN COMMENTS `cm` 
ON cm.id = c.id
LEFT JOIN Users `u`
ON c.userid = u.id
WHERE c.articleid = a.id
GROUP by itemid

Solution

  • You want to fetch all comments belonging to a post based on the article ID.

    The main parts are joining Comments and Article and then Users because the article has one-to-many relationships with comments and a comment has a one-to-one relationship with users.

    So use left join to fetch all comments from the article and join the User to Comments based on the user ID in Comments.

    SELECT  A.id as 'itemid',
        A.text as 'body',
        A.pic as 'itempic',
        U.name as 'authorname',
        U.pic as 'authorpic',
        C.id as 'commentId',
        C.text as 'commentBody'
    FROM Article AS A
    LEFT JOIN Comments AS C 
        ON C.articleid = A.id 
    JOIN users AS U
        ON U.id = C.userid
    WHERE A.id = 1;
    

    Sample Image result

    You can tweak the value picked from the query.