0

基本上我只是不确定为什么这个查询无法执行:

(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 行的“a INNER JOIN members ON replies.re”附近使用正确的语法

我要做的就是从这两个表中选择 5 个最近的行(日期)。我已经尝试过加入、联合等,并且我看到了许多查询,人们在 FROM 语句之后放置了另一个查询,而这对我来说是如何工作的没有逻辑意义?

我可以肯定地说您可以从两个不同但已连接的查询中连接同一个表吗?还是我采取了完全错误的方法,因为坦率地说,尽管阅读了错误消息,但我似乎看不到这个查询是如何失败的。

(那里的两个查询自己工作正常)

4

2 回答 2

1

我认为您的查询在以下部分存在语法错误:

FROM (posts) as b 
        WHERE posts.post_set = 0 
           INNER JOIN members ON posts.post_by = members.id)

内部连接应该在 where 条件之前。此外,您的加入条件是错误的。您需要应用条件,例如

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
于 2013-11-11T09:47:17.117 回答
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
于 2013-11-11T09:49:56.303 回答