将两个MySQL查询与共享结果组合在一起?

时间:2014-12-08 02:14:45

标签: 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')

此查询获取来自节点thread66的{​​{1}}表的所有结果,这些表没有匹配的78条目。因此,只有当没有匹配的文章条目时,才能返回一个线程并返回该线程。从理论上讲,这些查询不应该有匹配的数据。

然后我需要将这两个结果和article结合起来。

我将如何做到这一点?

2 个答案:

答案 0 :(得分: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');

答案 1 :(得分:0)

看来你可以这样做:

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