如何使用UNION组合两个具有ORDER BY的查询?

时间:2015-10-15 13:14:16

标签: mysql sql sql-order-by union-all

我有两个问题,每个问题都有自己的order by,如下所示:

查询1:

SELECT id, name, title, content 
FROM table where match(title, content) against('anything') 
Order By title

查询1:

SELECT id, tag, question, answer 
FROM table 
Where tag like '%anything' 
Order By tag, question

现在我如何使用UNION ALL组合它们?

2 个答案:

答案 0 :(得分:1)

如果您想保持相同的顺序,则以下内容通常有效:

(SELECT id, name, title, content
 FROM table
 where match(title, content) against('anything')
 order by title
) union all
(SELECT id, tag, question, answer
 FROM table
 where tag like '%anything'
 order by tag, question
);

这在实践中有效,因为实际上第一个子查询在第二个子查询之前执行。但是,我不认为MySQL文档保证了两者的处理顺序。对于该保证,您需要外部order by

(SELECT id, name, title, content, 1 as priority
 FROM table
 where match(title, content) against('anything')
) union all
(SELECT id, tag, question, answer, 2 as prioirty
 FROM table
 where tag like '%anything'
)
ORDER BY priority, title, content

答案 1 :(得分:1)

您需要按以下方式对结果进行排序:

  1. 结果类型(MATCH或LIKE)
  2. title(用于MATCH)或标签(用于LIKE)
  3. NULL(用于MATCH)或问题(用于LIKE)
  4. 您可以使用嵌套查询:

    SELECT * FROM (
        SELECT 1 AS result_type, id, name, title, content 
        FROM table
        WHERE MATCH (title, content) AGAINST ('anything') 
        UNION ALL
        SELECT 2, id, tag, question, answer 
        FROM table 
        WHERE tag LIKE '%anything' 
    ) AS foobar
    ORDER BY
        result_type,
        CASE result_type WHEN 1 THEN title ELSE tag END,
        CASE result_type WHEN 1 THEN NULL ELSE question END
    

    或者您可以添加排序助手列:

    (
    SELECT 1 AS sort_1, title AS sort_2, NULL     AS sort_3, id, name, title, content 
    FROM table
    WHERE MATCH (title, content) AGAINST ('anything') 
    ) UNION ALL (
    SELECT 2 AS sort_1, tag   AS sort_2, question AS sort_3, id, tag, question, answer 
    FROM table 
    WHERE tag LIKE '%anything' 
    )
    ORDER BY sort_1, sort_2, sort_3