我有一张桌子:
item_id | property_id | value |
================================
1 | 100 | 1 |
1 | 101 | 1 |
1 | 102 | 0 |
2 | 100 | 1 |
2 | 101 | 1 |
2 | 102 | 1 |
2 | 120 | black |
3 | 100 | 1 |
3 | 101 | 0 |
3 | 102 | 1 |
4 | 121 | big |
...
我想通过带有多个复选框和选择菜单的表单执行“AND”搜索(每个复选框和选择菜单的名称都像'property_id')。
示例:
已检查属性的数量(复选框和选择菜单)可能会有所不同。
我试过了:
SELECT item_id
FROM yourtable
WHERE property_id IN (100, 101)
AND value = 1
GROUP BY item_id
HAVING COUNT(DISTINCT property_id) = 2
但它仅适用于复选框和值0或1.我有选择菜单实现它的问题(示例2或3)。
我希望这可以解释我正在尝试做什么。 提前谢谢!
答案 0 :(得分:1)
对您的查询进行最少的更改:
SELECT item_id
FROM yourtable
WHERE property_id IN (100, 101)
AND value = 1
OR property_id = 120
AND value = 'black'
GROUP BY item_id
HAVING COUNT(DISTINCT property_id) = 3 ;
相当于:
SELECT item_id
FROM yourtable
WHERE property_id = 100 AND value = 1
OR property_id = 101 AND value = 1
OR property_id = 120 AND value = 'black'
GROUP BY item_id
HAVING COUNT(DISTINCT property_id) = 3 ;