基本上我只是不确定为什么这个查询无法执行:
(SELECT replies.reply_post, replies.reply_content, replies.reply_date AS d, members.username
FROM (replies) AS a
INNER JOIN members ON replies.reply_by = members.id)
UNION
(SELECT posts.post_id, posts.post_title, posts.post_date AS d, members.username
FROM (posts) as b
WHERE posts.post_set = 0
INNER JOIN members ON posts.post_by = members.id)
ORDER BY d DESC LIMIT 5
我收到了这个错误:
#1064
- 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法 在第2行的'一个INNER JOIN成员ON replies.re'附近
我要做的就是从这两个表中选择5个最近的行(日期)。我已经尝试了Join,union等,我已经看到了很多查询,人们在FROM语句之后放了另一个查询,这对我如何运作没有任何逻辑意义?
我可以肯定地说,您可以从两个不同但已加入的查询中加入同一个表吗?或者我采取了完全错误的方法,因为坦率地说,尽管阅读了错误信息,我似乎无法看到这个查询是如何失败的。
(关于那里的两个查询工作正常)
答案 0 :(得分:1)
我认为您的查询中存在语法错误:
FROM (posts) as b
WHERE posts.post_set = 0
INNER JOIN members ON posts.post_by = members.id)
内部联接应首先出现在条件之前。您的加入条件也是错误的。您需要应用
等条件INNER JOIN members ON a.reply_by = members.id)
INNER JOIN members ON b.post_by = members.id)
所以你的查询应该是这样的
(SELECT a.reply_post, a.reply_content, a.reply_date AS d, members.username
FROM (replies) AS a
INNER JOIN members ON a.reply_by = members.id)
UNION
(SELECT b.post_id, b.post_title, b.post_date AS d, members.username
FROM (posts) as b
INNER JOIN members ON b.post_by = members.id
WHERE b.post_set = 0)
ORDER BY d DESC LIMIT 5
答案 1 :(得分:1)
试试这个:
(SELECT a.reply_post, a.reply_content, a.reply_date AS d, members.username
FROM replies AS a
INNER JOIN members ON a.reply_by = members.id)
UNION
(SELECT b.post_id, b.post_title, b.post_date AS d, members.username
FROM posts as b
INNER JOIN members ON b.post_by = members.id
WHERE b.post_set = 0) /* Use where condition after matching Id's using ON */
ORDER BY d DESC LIMIT 5