SQL查询与OR不匹配

时间:2014-03-20 10:44:18

标签: mysql sql

我有这个SQL查询:

SELECT `CARD_ID`, `CARD_NAME`, `CARD_SET`,`CARD_COLOR` 
FROM (`All_Cards_Ext`)
WHERE (`CARD_NAME` LIKE '%hearts%' AND `CARD_COLOR` LIKE '%R%)
GROUP BY `CARD_NAME`LIMIT 9;

这个正常回归给我

--------------------------------------
51| Ace of Hearts | Bridge | R 
52| Jack of Hearts| Bridge | R

但是,下面的查询不会:

SELECT `CARD_ID`, `CARD_NAME`, `CARD_SET`,`CARD_COLOR`
FROM (`All_Cards_Ext`) 
WHERE (`CARD_NAME` LIKE 'hearts%' AND `CARD_COLOR` LIKE '%R%' OR `CARD_COLOR` LIKE '%B%' )GROUP BY `CARD_NAME`LIMIT 9;

这个不起作用它会返回随机记录,它似乎是OR正常工作后的标准:

  

-------------------------------------- 34| Ace of Diamonds | Bridge | D
35| Two of Diamonds | Bridge | D

...

5 个答案:

答案 0 :(得分:3)

WHERE (`CARD_NAME` LIKE 'hearts%' AND `CARD_COLOR` LIKE '%R%' OR `CARD_COLOR` LIKE '%B%' )GROUP BY `CARD_NAME`LIMIT 9;

应该是

WHERE (`CARD_NAME` LIKE 'hearts%' AND (`CARD_COLOR` LIKE '%R%' OR `CARD_COLOR` LIKE '%B%' )GROUP BY `CARD_NAME`LIMIT 9;

简单示例See Example

答案 1 :(得分:2)

您需要将您的OR条件分组为some and (someother or someother or someother )

SELECT `CARD_ID`, `CARD_NAME`, `CARD_SET`,`CARD_COLOR`
FROM (`All_Cards_Ext`) 
WHERE `CARD_NAME` LIKE 'hearts%' AND 
(`CARD_COLOR` LIKE '%R%' OR `CARD_COLOR` LIKE '%B%' )
GROUP BY `CARD_NAME`LIMIT 9;

答案 2 :(得分:2)

请注意您在哪里使用括号':

...
WHERE (`CARD_NAME` LIKE 'hearts%' AND (`CARD_COLOR` LIKE '%R%' OR `CARD_COLOR` LIKE '%B%'))
...

答案 3 :(得分:1)

为什么不用这个并摆脱OR ......

  AND `CARD_COLOR` in ( 'R' ,'B' ) 

而不是

  AND `CARD_COLOR` LIKE '%R%' OR `CARD_COLOR` LIKE '%B%' 
像那样:

 WHERE `CARD_NAME` LIKE 'hearts%' AND `CARD_COLOR` in ( 'R' ,'B' ) 

答案 4 :(得分:0)

我相信你在颜色比较中缺少括号 (CARD_NAME LIKE' hearts%' AND(CARD_COLOR LIKE'%R%'或CARD_COLOR LIKE'%B%')