2014-12-08 81 views
0

好了,所以我有一個查詢:結合兩個MySQL查詢共享結果?

SELECT *, articles.article_date AS article_date 
FROM articles 
    INNER JOIN thread ON (thread.thread_id = articles.thread_id) 
WHERE articles.article_date < 1417987751 

該查詢會從articles表中的所有結果,並使用從thread表中的數據加入他們。正如您所看到的,如果文章沒有匹配的線程條目,則無法返回文章。

現在我有另一個查詢:

SELECT *, thread.post_date AS article_date 
FROM thread 
    LEFT JOIN articles ON (articles.thread_id = thread.thread_id) 
WHERE articles.article_date IS NULL 
    AND thread.post_date < 1417987751 
    AND thread.node_id IN ('66','78') 

此查詢獲取從thread表來自節點6678,不具有匹配的article條目中的所有結果。所以一個線程可以被返回,並且只有當它沒有匹配的條目時纔會被返回。從理論上講,這些查詢不應該有匹配的數據。

然後我需要結合這兩個結果和ORDER BY article_date LIMIT 5

我該怎麼做呢?

+0

你是什麼意思? – 2014-12-08 02:23:38

回答

0

看來你可以這樣來做:使用`UNION`

SELECT *, COALESCE (articles.article_date, thread.post_date) AS _article_date 
FROM thread 
LEFT JOIN articles ON (articles.thread_id = thread.thread_id) 
WHERE 
    (articles.article_date is not NULL AND articles.article_date < 1417987751) 
    OR (articles.article_date IS NULL 
    AND thread.post_date < 1417987751 
    AND thread.node_id IN ('66','78')) 
ORDER BY 
_article_date 
LIMIT 5 
0

您可以檢查下面的查詢

SELECT *, thread.post_date AS article_date 
FROM thread 
    LEFT JOIN (
     SELECT * 
     FROM articles 
     ORDER BY article_date LIMIT 5) articles 
    ON (articles.thread_id = thread.thread_id) 
WHERE thread.post_date < 1417987751 
AND thread.node_id IN ('66','78'); 
+0

那不行。注意這兩個查詢中的'article_date'是不同的。 – 2014-12-08 02:38:11

+0

這也有一個重大故障。如果文章存在,但不在節​​點「66」或「78」中,則不會在此查詢中返回。我發佈的第一個查詢沒有節點限制,只有第二個查詢。 – 2014-12-08 02:48:13