MySql顺序与union重复结果

时间:2011-12-31 00:32:36

标签: mysql select sql-order-by union

这是我的查询

(SELECT *, 1 as ob FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%only three doors%" OR `joke` LIKE "%only three doors%") )
UNION
(SELECT *, 2 as ob FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%only%" OR `joke` LIKE "%only%") )
UNION
(SELECT *, 3 as ob FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%three%" OR `joke` LIKE "%three%") )
UNION
(SELECT *, 4 as ob FROM `jokes` WHERE `flags` < 5 AND (`title` LIKE "%doors%" OR `joke` LIKE "%doors%"))
 ORDER BY `ob` ASC, `ups` DESC,`downs` ASC LIMIT 0, 30

现在我的问题是我得到了重复的结果。有没有办法修改这个,所以我不会重复。

选择的顺序比起伏更重要。

我还要注意,select语句的数量会发生变化。

2 个答案:

答案 0 :(得分:1)

SELECT jokes.*
     , CASE WHEN title LIKE '%only three doors%' 
              OR joke LIKE '%only three doors%'
              THEN 1 
            WHEN title LIKE '%only%' 
              OR joke LIKE '%only%'
              THEN 2
            WHEN title LIKE '%three%' 
              OR joke LIKE '%three%'
              THEN 3
            ELSE 4
       END as ob 
FROM jokes 
WHERE flags < 5 
  AND ( title LIKE '%only%' 
     OR joke LIKE '%only%'
     OR title LIKE '%three%' 
     OR joke LIKE '%three%'
     OR title LIKE '%doors%' 
     OR joke LIKE '%doors%'
      )
ORDER BY ob ASC
       , ups DESC
       , downs ASC 
LIMIT 0, 30

答案 1 :(得分:0)

您显然会得到重复的结果,因为您在SELECT *之后添加了字面数值。

这将使每一行不同,因此UNION将无法删除其他重复的行。