有没有更好的查询来解决这个问题?
1车有很多种类型。
我想要这样的事情:(ps这是不正确的,我知道)
select * from car join type on car.id = type.id_car
where type = 'SUV'
and type = '4x4'
and (type = 'blue' or type = 'red')
and type = 'US'
and (type = 'Manual' or type = 'Automatic' or 'SemiAutomatic')
and type = 'diesel' and so on.
我的解决方案是:
select * from car
where numberOfANDType = (select count(1) from Type where car.id = type.id_car and type in ('suv', '4x4', 'us', 'diesel'))
and exists (select 1 from type where car.id = type.id_car and type in ('blue', 'red'))
and exists (select 1 from type where car.id = type.id_car and type in ('manual', 'automatic' or 'SemiAutomatic');
等等。
ps:我知道AND的使用条件数 ps2:这些条件是动态的。
无论如何:我对每个类型都有一个GROUP列,对于OR组中使用的类型,我在此列中具有相同的值。 SUV具有GROUP = 1,蓝色具有GROUP = 2,红色具有GROUP = 2,依此类推。 所以我对TYPE列和组上的计数进行查询,以查看是否所有组都被覆盖。
Select id from car join type on .. where type in ('SUV', 'blue', 'red') group by id having count(distinct group) > 2;
感谢。
ps3:感谢所有关注这个问题的人,你很善良。
答案 0 :(得分:2)
我认为解决这个问题的更好方法是具体说明类型并为这些创建列:
select * from car
where type = 'SUV'
and drive_type = '4x4'
and (colour = 'blue' or colour = 'red')
and origin = 'US'
and (transmission = 'Manual' or transmission = 'Automatic')
and fuel_type = 'diesel'
然后,您可以使用索引来提高查询的性能。
答案 1 :(得分:2)
扩展我对Cosmin答案的评论,这应该有效:
select car.id
from car
join type on car.id = type.id_car
where type.type in
('SUV','4x4','blue','red','US','Manual','Automatic','SemiAutomatic','diesel')
group by car.id
having count(distinct type.group)=6
答案 2 :(得分:0)
这样就可以了:
select car.*
from car INNER JOIN (
select id, count(*) countMatches
from car INNER JOIN type on car.id = type.id_car
where type in ('suv', '4x4', 'us', 'diesel','blue',
'red','manual', 'automatic')
group by id
having count(*) = 6
) matches ON car.id = matches.id
答案 3 :(得分:0)
select * from car c1 where c1.id in
(
select c.id from car c
inner join Type t on c.id = t.id_car and c.type in ('suv', '4x4', 'us', 'diesel', 'blue', 'red', 'manual', 'automatic')
group by c.id
having count(distinct *) > 5
)
答案 4 :(得分:0)
你的设计不好。
每个组值都应该进入一个新列。
所以类型表应该是:
id_car color transmission fuel origin_country etc
1 blue automatic gas UK
....
查询将是:
select *
from car join type on (car.id = type.id_car)
where color in ('red', 'blue')
and transmision in ('automatic')
and country in ('US')
etc.