简体   繁体   English

mySQL中2个表的Select数据,加入

[英]Select data from 2 tables in mySQL, join it

I need to select data from 2 tables in my DB - comments and users.我需要 select 数据来自我的数据库中的 2 个表 - 评论和用户。 This is the structure of these tables:这是这些表的结构:

comments :评论

commentID |评论ID | commentDateAndTime |评论日期和时间 | imageID |图片ID | 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 .我需要 select 两个表中的所有数据,将其加入 userID,其中 imageID 应等于$imageID I tried the following SELECT statement:我尝试了以下SELECT语句:

    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?有什么建议吗?

Why are you using group by if you need all the result.如果您需要所有结果,为什么要使用 group by。

SELECT users.* , comments.*
FROM users JOIN comments ON comments.userID = users.userID 
WHERE comments.imageID = $imageID 

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" ). MySQL 执行自动连接(从此页面开始: “FROM [...] 子句指示要从中检索行的一个或多个表。如果您命名多个表,则您正在执行连接” )。

Also, since there are two userID columns you need to be specific of which one by preceding the table name.此外,由于有两个userID列,您需要在表名前指定具体是哪一个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM