2014-01-14 42 views
0

我有下面列出的查詢,它是從一個PDO語句。除了collectionId = 3部分之外,查詢中的所有內容都可以正常工作。它與其他整數的返回結果...mysql查詢沒有篩選和按預期

我盯着這一段時間,不能發現什麼是錯的,這一切對我來說都很好嗎?

SELECT `Hat`.`id` AS `Hat_id` , `Hat`.`hatCode` AS `Hat_hatCode` , `Hat`.`hatCodeOther` AS `Hat_hatCodeOther` , `Hat`.`name` AS `Hat_name` , `Hat`.`description` AS `Hat_description` , `Hat`.`colorId` AS `Hat_colorId` , `Hat`.`collectionId` AS `Hat_collectionId` , `Hat`.`mainPicture` AS `Hat_mainPicture` , `Hat`.`subPicture` AS `Hat_subPicture` , `Hat`.`type` AS `Hat_type` , `Hat`.`featured` AS `Hat_featured` , `Hat`.`published` AS `Hat_published` , `Hat`.`deleted` AS `Hat_deleted` 
FROM `modx_hats` AS `Hat` 
WHERE (
`Hat`.`published` =1 
AND `Hat`.`collectionId` = '3' 
AND `Hat`.`colorId` LIKE '%||2||%' 
OR `Hat`.`colorId` LIKE '2||%' 
OR `Hat`.`colorId` LIKE '%||2' 
OR `Hat`.`colorId` LIKE '2' 
) 
LIMIT 0 , 30 
+0

退房SQL操作precendence這個問題:http://stackoverflow.com/questions/1241142/sql-logic-operator-precedence-and-和 - 或 – vbo

+0

可能重複的[SQL查詢多個AND和OR不工作](http://stackoverflow.com/questions/21096134/sql-query-multiple-and-ors-not-working) – codeling

回答

1

你OR條件需要在括號:

SELECT `Hat`.`id` AS `Hat_id` , `Hat`.`hatCode` AS `Hat_hatCode` , `Hat`.`hatCodeOther` AS `Hat_hatCodeOther` , `Hat`.`name` AS `Hat_name` , `Hat`.`description` AS `Hat_description` , `Hat`.`colorId` AS `Hat_colorId` , `Hat`.`collectionId` AS `Hat_collectionId` , `Hat`.`mainPicture` AS `Hat_mainPicture` , `Hat`.`subPicture` AS `Hat_subPicture` , `Hat`.`type` AS `Hat_type` , `Hat`.`featured` AS `Hat_featured` , `Hat`.`published` AS `Hat_published` , `Hat`.`deleted` AS `Hat_deleted` 
FROM `modx_hats` AS `Hat` 
WHERE (
`Hat`.`published` =1 
AND `Hat`.`collectionId` = '3' 
AND (`Hat`.`colorId` LIKE '%||2||%' 
OR `Hat`.`colorId` LIKE '2||%' 
OR `Hat`.`colorId` LIKE '%||2' 
OR `Hat`.`colorId` LIKE '2') 
) 
LIMIT 0 , 30 
+0

這就是它 - 謝謝,因爲這是第一個正確的答案,我會接受這一點,當我被允許。將upvote所有其他雖然:) –

1

你可以試試這個,新增()爲或分組

WHERE (
`Hat`.`published` =1 
AND `Hat`.`collectionId` = '3' 
AND (`Hat`.`colorId` LIKE '%||2||%' 
OR `Hat`.`colorId` LIKE '2||%' 
OR `Hat`.`colorId` LIKE '%||2' 
OR `Hat`.`colorId` LIKE '2' 
) 
) 

編號:SQL Query multiple AND and OR's not working

0

你不」請指定您想要過濾的內容,但您的問題很可能是情況t的評估與您的想法不同 - 您如何評估OR和AND(沒有括號將它們分組)?

目前的情況是,該查詢返回一個滿足所有記錄無論是

`Hat`.`published` =1 AND 
`Hat`.`collectionId` = '3' AND 
`Hat`.`colorId` LIKE '%||2||%' ` 

OR其履行其中的任何其他限制:

OR `Hat`.`colorId` LIKE '2||%' 
OR `Hat`.`colorId` LIKE '%||2' 
OR `Hat`.`colorId` LIKE '2' 

這是設置括號權的所有問題。 我的猜測是你想要發佈所有記錄= 1,collectionId = 3和你給出的一個colorIds。 對於這一點,你必須組會相應:

WHERE (
`Hat`.`published` =1 
AND `Hat`.`collectionId` = '3' 
AND 
    (
    `Hat`.`colorId` LIKE '%||2||%' 
    OR `Hat`.`colorId` LIKE '2||%' 
    OR `Hat`.`colorId` LIKE '%||2' 
    OR `Hat`.`colorId` LIKE '2' 
) 
)