Mysql Union返回重复项

时间:2017-07-10 16:52:56

标签: mysql sql

我有这个查询

(
SELECT u.Id, 1 AS which
FROM users u
JOIN user_opt uo ON u.id = uo.UserId
WHERE uo.country
IN (
'Spain',  'Azerbaijan'
)
AND uo.Hobbies REGEXP  'Astronomy'
LIMIT 100
)
UNION (

SELECT u.Id, 2 AS which
FROM users u
JOIN user_opt uo ON u.id = uo.UserId
WHERE uo.country
IN (
'Spain',  'Azerbaijan'
)
LIMIT 100
)
ORDER BY which 

因为我在这个查询中使用UNION我不应该得到重复的行。但这会返回重复的行。

1 个答案:

答案 0 :(得分:1)

你应该能够非常接近你想做的事情:

(SELECT u.Id, 1 AS which
 FROM users u JOIN
      user_opt uo
      ON u.id = uo.UserId
 WHERE uo.country IN ('Spain',  'Azerbaijan') AND
       uo.Hobbies REGEXP 'Astronomy'
 LIMIT 100
)
UNION ALL
(SELECT u.Id, 1 AS which
 FROM users u JOIN
      user_opt uo
      ON u.id = uo.UserId
 WHERE uo.country IN ('Spain',  'Azerbaijan') AND
       uo.Hobbies NOT REGEXP 'Astronomy'
 LIMIT 100
)

这不是保证将第一组放在第一位。但在实践中,确实如此。