超复杂的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个查询吗?如果是这样如何?如果没有,我可以结合两个查询,然后订购它们?
答
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
类似的东西。
mysql和sql在语法上有一些不同,请选择正确的标记 – diEcho 2011-05-26 19:57:42
抱歉修好了。 – John 2011-05-26 19:58:46