当前位置: 代码迷 >> PHP >> mysql UNION 有重复的数据,如何解决
  详细解决方案

mysql UNION 有重复的数据,如何解决

热度:10   发布时间:2016-04-29 00:50:09.0
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 xhFROM textWHERE (id <312AND `title` LIKE '%德国%'AND `title` LIKE '%丹麦%')UNION SELECT * , 2 AS xhFROM textWHERE (id <312AND (`title` LIKE '%德国%')+(`title` LIKE '%丹麦%') = 1ORDER BY xhLIMIT 6
  相关解决方案