在以下查询中,用户获得了特定汽车的所有详细信息;例如:车轮-红色,座椅-蓝色
SELECT mc.car_name,
GROUP_CONCAT(CONCAT(cp.car_parts, ' - ', cd.car_detail) separator ',') AS
detail_values
FROM my_cars mc
LEFT JOIN cars_detail cd ON mc.id = cd.id_car
LEFT JOIN car_parts cp ON cd.id_parts = cp.id_parts
WHERE id_car = 1
GROUP BY car_name;
当用户进行搜索(例如用作参数)时,颜色“红色”应返回完全相同的值;也就是说,用户希望获得汽车的所有细节,其中一个细节是颜色“红色”
SELECT mc.car_name,
GROUP_CONCAT(CONCAT(cp.car_parts, ' - ', cd.car_detail) separator ',') AS detail_values
FROM my_cars mc
LEFT JOIN cars_detail cd ON mc.id = cd.id_car
LEFT JOIN car_parts cp ON cd.id_parts = cp.id_parts
WHERE id_car = 1
AND cd.car_detail LIKE 'red' //Illustrative example that returns a wrong result
GROUP BY car_name;
该怎么做?
这是一个SQL提琴:http://www.sqlfiddle.com/#!9/6f26b4/4
答案 0 :(得分:0)
使用exists
是满足您条件的快速解决方案,如果在同一查询中对汽车属性cars_detail
应用过滤器,则相关行将被过滤掉,而GROUP_CONCAT
将不显示排除的属性汽车。
SELECT mc.car_name,
GROUP_CONCAT(CONCAT(cp.car_parts, ' - ', cd.car_detail) separator ',') AS detail_values
FROM my_cars mc
LEFT JOIN cars_detail cd ON mc.id = cd.id_car
LEFT JOIN car_parts cp ON cd.id_parts = cp.id_parts
WHERE id_car = 1
AND EXISTS(
SELECT 1
FROM cars_detail
WHERE car_detail LIKE 'red'
AND cd.id_car = id_car
)
GROUP BY car_name