我有两个表(vehicles,available_colors)如下,
id vehicle_name
-- ------------
1 Honda Dio
2 Yamaha FZ
3 RE Classic 350
id vehicle_id color
-- ---------- ----
1 1 Red
2 1 Yello
3 1 White
4 1 Black
5 2 Metalic Red
6 2 Metalic Black
7 2 Metalic Blue
8 3 Classic Red
9 3 Classic Black
10 3 Classic Silver
我想用以下标准执行操作
IF available_colors.color LIKE '%Metalic Red%'
THEN return that "vehicle" with all the "available colors",
id vehicle_name color
-- ------------ -----
2 Yamaha FZ Metalic Red
2 Yamaha FZ Metalic Black
2 Yamaha FZ Metalic Blue
答案 0 :(得分:4)
SELECT * FROM vehicles V1
JOIN available_colors AC1 ON V1.id = AC1.vehicle_id
WHERE EXISTS
( SELECT * FROM available_colors ac
where ac.vehicle_id = v.id and ac.color like '%Metalic Red%')
答案 1 :(得分:1)
这个问题有两个部分 - 第一部分是用相应的颜色连接每辆车。第二,只选择金属红中存在的车辆:
SELECT vehicles.id, vehicle_name, color
FROM vehicles
JOIN available_colors ON vehicles.id = available_colors.vehicle_id
WHERE EXISTS (SELECT 1
FROM available_colors
WHERE color LIKE '%Metallic Red%' AND
vehicles.id = available_colors.vehicle_id)
答案 2 :(得分:0)
加入两个表并尝试:
select a.id, a.vehicle_name, b.color from vehicles a inner join available_colors b on
a.id=b.vehicle_id where b.color like '%Metallic red%'
答案 3 :(得分:0)
您的查询应该是这样的
Select v.vehicle_name,ac.color From vehicles v LEFT JOIN available_colors ac ON ac.vehicle_id = v.id WHERE ac.color LIKE %Metalic%
答案 4 :(得分:0)
如果您愿意为每辆车获得单行颜色,您可以这样做:
select v.id, v.vehicle_name, group_concat(ac.color) as colors
from vehicles v join
available_colors ac
on v.id = ac.vehicle_id
group by v.id, v.vehicle_name
having sum(ac.color LIKE '%Metalic Red%) > 0;