这让我头疼。我将尝试根据用户帖子数据库给出一个很好的例子。

表1具有帖子的正文以及作者的唯一POSTID和USERNAME。

Table2包含帖子ID(与Table1中的postid匹配)所引用的帖子(LIKES)的“喜欢”数。

允许用户在其页面上“共享”其他人的帖子。所以...

Table3包含共享帖子的POSTID以及共享它的用户的USERNAME。

您要在用户页面上显示他的帖子列表以及他要分享的帖子。因此,我们需要从table1(他是USERNAME)中获取帖子的所有POSTID,并添加到table3(他是USERNAME)中的所有POSTID,然后按照table2中LIKES的数量对所有POSTID进行排序。

这是我尝试的:

SELECT postid
FROM posts_views_likes
LEFT JOIN posts USING (postid)
LEFT JOIN shared_posts USING (postid)
WHERE posts.username = 'abbsmalone'
UNION
SELECT postid
FROM posts_views_likes
LEFT JOIN posts USING (postid)
LEFT JOIN shared_posts USING (postid)
WHERE shared_posts.username = 'abbsmalone'
ORDER BY posts_views_likes.likes DESC


我也尝试过...

SELECT postid
FROM posts
LEFT JOIN posts_views_likes USING (postid)
LEFT JOIN shared_posts USING (postid)
WHERE posts.username = 'abbsmalone'
UNION
SELECT postid
FROM shared_posts
LEFT JOIN posts_views_likes USING (postid)
LEFT JOIN posts USING (postid)
WHERE shared_posts.username = 'abbsmalone'
ORDER BY posts_views_likes.likes DESC


显然,这是行不通的。我不断收到一条错误消息,指出#1054-“ order子句”中的未知列“ likes”

我认为这样的事情是可能的吗?

更新:

我也尝试过:

SELECT postid, posts_views_likes.likes
FROM posts
LEFT JOIN posts_views_likes USING (postid)
LEFT JOIN shared_posts USING (postid)
WHERE posts.username = 'abbsmalone'
UNION
SELECT postid, posts_views_likes.likes
FROM posts_views_likes
LEFT JOIN posts USING (postid)
LEFT JOIN shared_posts USING (postid)
WHERE shared_posts.username = 'abbsmalone'
UNION
SELECT postid, posts_views_likes.likes
FROM shared_posts
LEFT JOIN posts_views_likes USING (postid)
LEFT JOIN posts USING (postid)
WHERE posts.username = 'abbsmalone' OR shared_posts.username = 'abbsmalone'
ORDER BY posts_views_likes.likes DESC


但是我得到了同样的错误。

更新已修复:

我终于弄清楚了,这比我尝试做起来容易得多。

SELECT postid, posts_views_likes.ratio, posts.username
FROM posts
LEFT JOIN posts_views_likes USING (postid)
LEFT JOIN shared_posts USING (postid)
WHERE posts.username = 'abbsmalone'
OR shared_posts.username = 'abbsmalone'
ORDER BY posts_views_likes.ratio DESC

最佳答案

要让您的ONE order子句对并集的结果进行排序,您必须将查询编写为

(SELECT ...)
UNION ALL
(SELECT ...)
ORDER BY ...


按照the docs(搜索to sort or limit the entire)。

而且根据文档,您不能使用表名称来引用查询结果中的字段。您必须在各个查询中提供别名:

(SELECT foo AS bar ...)
UNION ALL
(SELECT baz AS bar ...)
ORDER BY bar

关于mysql - 完全联接3张 table ,并按一个顺序订购,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31438495/

10-13 06:26