日期:2014-05-17  浏览次数:20596 次

mysql UNION 有重复的数据,怎么解决?
SELECT * , 1 AS xh
FROM text
WHERE (
id <312
AND `title` LIKE '%德国%'
AND `title` LIKE '%丹麦%'
)
UNION SELECT * , 2 AS xh
FROM text
WHERE (
id <312
AND `title` LIKE '%德国%'
OR `title` LIKE '%丹麦%'
)
ORDER BY xh
LIMIT 6

------解决方案--------------------
改成'x''X'.....这么诡异的注意你也能想出来....嗯, 至少要加个注释,要不将来被N个读代码的骂不要怪我.....

关于括号: 
id <312 AND `title` LIKE '%德国%' OR `title` LIKE '%丹麦%'
相当于 ( id <312 AND `title` LIKE '%德国%' ) OR `title` LIKE '%丹麦%' 

这个和
 id <312 AND ( `title` LIKE '%德国%' OR `title` LIKE '%丹麦%' )
是不同的, 应该明白了吧, 

还不明白加条 有"丹麦"并且 id>312的记录 并且能让它排进前6的话就明白了
------解决方案--------------------
不至于搞得那么复杂吧?
SQL code
SELECT * , 1 AS xh
FROM text
WHERE (
id <312
AND `title` LIKE '%德国%'
AND `title` LIKE '%丹麦%'
)
UNION SELECT * , 2 AS xh
FROM text
WHERE (
id <312
AND (`title` LIKE '%德国%')+(`title` LIKE '%丹麦%') = 1
ORDER BY xh
LIMIT 6