2011-05-26 124 views
0

有一篇文章模型,每篇文章都有一個作者和發佈者(都是表格)。用戶可以關注作者和發佈者。超複雜的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

回答

1
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

0
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 

這應該爲你工作。

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

我的頭頂部:

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

0

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

類似的東西。