MySQL - UNION DISTINCT,附加列

时间:2017-12-01 13:46:41

标签: mysql distinct union

我正在尝试在我的一个应用程序中进行“搜索”的MySQL查询。这就是我目前所拥有的:

(SELECT id, title, 1 AS `order`
    FROM tasks
    WHERE title LIKE '%Task%Test%')
UNION DISTINCT
(SELECT id, title, 2 AS `order`
    FROM tasks
    WHERE title LIKE '%Task%' AND title LIKE '%Test%')
ORDER BY `order` ASC;

UNION类型的第二个查询充当第一个查询的回退,因为第一个查询期望这些单词的顺序相同。 (单词的数量是动态的,具体取决于搜索查询。)

在结果中,我想首先显示第一个查询的结果,因为它们更精确。为此,我尝试在结果中添加一个额外的列:order

我的问题是,DISTINCT仅适用于完全相同的行,但由于orders列,我的行不是这种情况。

示例

表:

id    title
1     'Test Task'
2     'The Second Test Task'
3     'A Third Task For Testing'
4     'A Fourth Test'

结果:

id    title                         order
3     'A Third Task For Testing'    1
1     'Test Task'                   2
2     'The Second Test Task'        2
3     'A Third Task For Testing'    2

我想要的是什么:

id    title                         order
3     'A Third Task For Testing'    1
1     'Test Task'                   2
2     'The Second Test Task'        2

任何可以帮助我的人?​​

提前致谢!

2 个答案:

答案 0 :(得分:2)

我认为你可以在不使用union的情况下从单个查询中获得相同的结果:

SELECT
    id, title,
    CASE WHEN title LIKE '%Task%Test%' THEN 1
         WHEN title LIKE '%Task%' AND title LIKE '%Test%' THEN 2
         ELSE 3
    END AS label
FROM tasks
WHERE
    title LIKE '%Task%Test%' OR
    (title LIKE '%Task%' AND title LIKE '%Test%')
ORDER BY label;

Demo

答案 1 :(得分:1)

您可以使用group by:

SELECT id, title, `order`
    FROM (
        (SELECT id, title, 1 as `order`
         FROM tasks
         WHERE title LIKE '%Task%Test%')
        UNION DISTINCT
        (SELECT id, title, 2 as `order`
         FROM tasks
         WHERE title LIKE '%Task%' AND title LIKE '%Test%')

    ) tb
GROUP BY id
ORDER BY `order` ASC;