我有这个查询
(
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
我不应该得到重复的行。但这会返回重复的行。
答案 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
)
这不是保证将第一组放在第一位。但在实践中,确实如此。