超复杂的SQL查询

问题描述:

有一篇文章模型,每篇文章都有一个作者和发布者(都是表格)。用户可以关注作者和发布者。超复杂的SQL查询

用户 - >按 - >作者或出版商 - >文章

我想找到他们遵循了作者和出版商的所有文章。

SELECT articles.*, articles2.* FROM follows 
INNER JOIN articles ON follows.author_id = articles.author_id 
INNER JOIN articles AS articles2 ON follows.publisher_id = articles2.publisher_id 
WHERE follows.user_id = 1 

我可以将所有文章转换为1个查询吗?如果是这样如何?如果没有,我可以结合两个查询,然后订购它们?

+0

mysql和sql在语法上有一些不同,请选择正确的标记 – diEcho 2011-05-26 19:57:42

+0

抱歉修好了。 – John 2011-05-26 19:58:46

select a.* from follows f 
inner join articles a on (a.author_id = f.author_id or a.publisher_id=f.publisher_id) 
where f.user_id = 1 
+0

不错的答案;),你快4秒! – Zoidberg 2011-05-26 19:59:24

+0

猜猜这毕竟不是那么辛苦。万分感谢。花了最后3个小时试图找出答案。 – John 2011-05-26 20:02:33

+0

jep,和你一样hehehe :) – 2011-05-26 20:05:48

SELECT articles.*, articles2.* FROM follows 
INNER JOIN articles ON (follows.author_id = articles.author_id OR follows.publisher_id = articles.publisher_id) 
WHERE follows.user_id = 1 

这应该为你工作。

SELECT articles.* FROM follows,articles 
WHERE follows.user_id = 1 
AND (follows.author_id = articles.author_id 
    OR follows.publisher_id = articles2.publisher_id) 

我的头顶部:

SELECT文章* FROM如下 INNER JOIN文章ON follows.author_id = articles.author_id WHERE follows.user_id = 1

UNION

SELECT articles。* FROM follow INNER JOIN articles on following.publisher_id = articles.publisher_id WHERE following.user_id = 1 ORDER BY articles.title

SELECT文章。* FROM如下INNER JOIN文章ON follows.author_id = articles.author_id

UNION ALL

SELECT articles2。* FROM如下INNER JOIN文章AS articles2 ON如下.publisher_id = articles2.publisher_id

类似的东西。