如何让mysql requst选择包含list的所有元素的所有值。 我有这样的表:
+--------+------------+
| carID | serviceID |
+--------+------------+
| 1 | 12 |
+--------+------------+
| 1 | 13 |
+--------+------------+
| 1 | 15 |
+--------+------------+
| 2 | 12 |
+--------+------------+
| 3 | 13 |
+--------+------------+
| 3 | 15 |
+--------+------------+
我提出的请求如下:
SELECT `carID` FROM `car_services` WHERE `carID` in (1, 2, 3) AND `serviceID` in (12, 13, 15);
但它会返回所有车辆,但我只需要carID = 1
车,因为只有这辆车适合这种情况(支持所有服务12,13,15)。
有什么想法吗?
答案 0 :(得分:1)
一种简单的方法是group by
和having
SELECT `carID`
FROM `car_services`
WHERE `carID` in (1, 2, 3) AND `serviceID` in (12, 13, 15)
group by carID
having count(*) = 3
;
答案 1 :(得分:0)
使用GROUP BY
和HAVING
条款:
SELECT `carID`
FROM `car_services`
WHERE `carID` in (1, 2, 3)
GROUP BY `carID`
HAVING SUM(CASE WHEN `serviceID` in (12,13,15) THEN 1 ELSE 0 END)=3
答案 2 :(得分:0)
使用复合where子句来单独检查EXISTS非常简单,并且不依赖于serviceid-carid关系的唯一性。我看一下查询计划/执行成本,然后决定它实际上比分组解决方案更好(如果它是唯一的。)
SELECT carID
FROM car_services a
WHERE EXISTS (SELECT 1 FROM car_services b WHERE a.carID = b.car_id AND serviceID = 12)
AND EXISTS (SELECT 1 FROM car_services b WHERE a.carID = b.car_id AND serviceID = 13)
AND EXISTS (SELECT 1 FROM car_services b WHERE a.carID = b.car_id AND serviceID = 15)
注意:对于许多必需的服务而言,这显然不能很好地扩展。
答案 3 :(得分:0)
您可以使用GROUP_CONCAT
:
SELECT carID
FROM (
SELECT carID,
GROUP_CONCAT(DISTINCT serviceID ORDER BY serviceID) AS allServices
FROM car_services
WHERE serviceID in (12, 13, 15)
GROUP BY carID ) t
WHERE allServices = "12,13,15";
即使您在serviceID
字段中有重复项,这也会有用。