使用 AND 和 OR 的 Oracle SQL 动态查询性能更高
有没有更好的查询来解决这个问题?
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:这些条件是动态的。
不管怎样:我为每个类型都有一个组列,并且对于 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:感谢所有对这个问题投反对票的人,你们非常友善。
Is there a better query to solve this problem ?
1 Car has many Types.
I want something like this: (ps this is incorrect, i know)
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.
My solution is:
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');
And so on.
ps: I know the number of conditions used with AND
ps2: these conditions are dynamic.
Anywayz: i have for each Type a GROUP Column, and for the Types used in groups of OR i have the same value in this column. SUV has GROUP = 1, blue has GROUP = 2, red has GROUP = 2 and so on.
So I make a query on the TYPE Column and the count on the group, to see if all groups are covered.
Select id from car join type on .. where type in ('SUV', 'blue', 'red') group by id having count(distinct group) > 2;
Thanks.
ps3: thanks to all who downvoted this question, you are very kind.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这样就可以做到:
This would do it:
扩展我对 Cosmin 答案的评论,这应该有效:
Expanding on my comment to Cosmin's answer, this should work:
我认为解决这个问题的更好方法是具体说明类型并为这些类型创建列:
然后您可以使用索引来提高查询的性能。
I think a better way of solving this would be to be specific about the types and create columns for these:
Then you can use indexes to improve the performance of the query.
你的设计很糟糕。
每个组值都应该进入一个新列。
所以类型表应该是:
查询是:
You have a bad design.
Every group value shoud go into a new column.
So the type table should be:
The query would be: