1

I need to select data from 2 tables in my DB - comments and users. This is the structure of these tables:

comments:

commentID | commentDateAndTime | imageID | userID | comment

users:

userID | username

I need to select all the data in both tables, join it on userID, where imageID should be equal to $imageID. I tried the following SELECT statement:

    return json_encode(select("
    SELECT
     commentDateAndTime,
     imageID,
     userID,
     COMMENT,
     username
   FROM users
    JOIN comments
    ON comments.userID = users.userID
   WHERE comments.imageID = $imageID
   GROUP BY comments.comment   
"));

But I didn't receive any data.

Any advice, please?

4
  • 2
    Why do you need the group by? doesn't look like you're using it. Commented Apr 9, 2012 at 8:28
  • 1
    Try remove GROUP BY comments.comment Commented Apr 9, 2012 at 8:29
  • @diEcho Yup, that worked. I also changed SELECT commentDateAndTime, imageID, userID, comment, username to SELECT * Now worked fine! Thank you! Commented Apr 9, 2012 at 8:35
  • @AlexAckerman: Throw that in an answer so that lgal can close this question out. Commented Apr 9, 2012 at 12:34

2 Answers 2

4

Why are you using group by if you need all the result.

SELECT users.* , comments.*
FROM users JOIN comments ON comments.userID = users.userID 
WHERE comments.imageID = $imageID 
Sign up to request clarification or add additional context in comments.

Comments

2

MySQL does auto-joins (from this page: "The FROM [...] clause indicates the table or tables from which to retrieve rows. If you name more than one table, you are performing a join").

Also, since there are two userID columns you need to be specific of which one by preceding the table name.

So your query could be like this:

SELECT commentDateAndTime, imageID, users.userID AS userID, comment, username
FROM comments, users
WHERE comments.userID = users.userID AND comments.imageID = $imageID

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.