使用 Left Join 和Where IN 子句的 MYSQL 查询

标签 mysql join left-join

我有三个表 A B C,我正在尝试从这三个表中检索信息。

A 具有列 userid 头像用户名,B 具有列 postid, dateshared,C 具有列评论者 postid datecommented。

我正在尝试运行查询

Select  C.comment, C.commenter,  C.datecommented, B.postid, B.dateshared A.username A.avatar from B Left Join C  Left join A on C.postid = B.postid AND A.userid = C.commenter where B.postid IN ('1','2','3') order by  C.dateshared desc

但它给出了以下错误:

 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where B.postid IN ('1', '2', '3') order by C.dateshared '

任何人都可以指出我做错了什么或建议如何解决吗?

最佳答案

每个 LEFT JOIN 都需要自己的 ON 条件:

SELECT  C.comment, C.commenter, C.datecommented, B.postid, B.dateshared, A.username A.avatar
FROM    B
LEFT JOIN
        C
ON      C.postid = B.postid
LEFT JOIN
        A
ON      A.userid = C.commenter
WHERE   B.postid IN ('1','2','3')
ORDER BY
        C.dateshared desc

关于使用 Left Join 和Where IN 子句的 MYSQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16071871/

相关文章:

mysql - 同时选择该字段的最小日期和最大日期

sql-server - 如何在 SQL Server 中同时使用 PIVOT 和 JOIN?

php - mysql : Products which satisfies category conditions

用于嵌套左连接的 C# Linq 表达式

mysql - 减少 MySQL 查询时间(目前已运行 24 小时且仍在继续)

mysql - 如何在 select 语句中添加新列

sql - 如何在 PostgreSQL 中的连接中使用 Case 语句?

mysql - 使用 Junction Table 加入 MANY to MANY

mysql - 查询 : Count how many times a parameter in one table does not exist in another

python - 如何使用 Django、MySQL 输出某些计算值的对数