带有复杂子查询的 SQL 查询
我有两张桌子,Foo 和 Bar。 Foo 包含 Bar 的主键 (bar_id) 的外键。 Bar 的结构允许通过 Bar 中另一条记录的外键 (bar_parent_id) 与其自身建立父/子关系。这种关系是有限的,因此任何具有父级的 Bar 记录本身都不能是父级。然而,任何一个父母都可以有多个孩子。
我的查询需要选择 Foo 中与 Bar 中给定记录匹配的所有记录以及 Bar 的父母、孩子或兄弟姐妹。下面的查询可以工作,但速度有点慢。有什么方法可以使其运行得更快吗?
SELECT f.field1, f.field2
FROM Foo f
WHERE f.bar_id IN (
SELECT bar_id
FROM Bar
WHERE bar_id = @bar_id OR
bar_parent_id = @bar_id OR
bar_id = (SELECT bar_parent_id FROM Bar WHERE bar_id = @bar_id) OR
bar_parent_id = (SELECT bar_parent_id FROM Bar WHERE bar_id = @bar_id AND bar_parent_id > 0)
)
PS 这是真实查询的简化版本。它实际上有第二个相同的子查询到另一个表,该表与 Bar 具有相同的自/父/子关系。
I have two tables, Foo and Bar. Foo contains a foreign key to Bar's primary key (bar_id). Bar is structured to allow a parent/child relationship to itself through a foreign key (bar_parent_id) to another record in Bar. This relationship is limited such that any Bar record that has a parent cannot itself be a parent. However, any given parent can have multiple children.
My query needs to select all of the records in Foo that match a given record in Bar as well any of the Bar's parents, children or siblings. The query below works, but is somewhat slow. Is there any way to structure it so that it will run faster?
SELECT f.field1, f.field2
FROM Foo f
WHERE f.bar_id IN (
SELECT bar_id
FROM Bar
WHERE bar_id = @bar_id OR
bar_parent_id = @bar_id OR
bar_id = (SELECT bar_parent_id FROM Bar WHERE bar_id = @bar_id) OR
bar_parent_id = (SELECT bar_parent_id FROM Bar WHERE bar_id = @bar_id AND bar_parent_id > 0)
)
P.S. This is a simplified version of the real query. It actually has a second, identical subquery to another table that has the same self/parent/child relationship as Bar.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以尝试一下,但我不确定正确性
You can try but I'm not sure of the correctness
试试这个:
Try this:
OR 通常会减慢 SQL 查询的速度。另一种可能性能更好的替代方案是合并单独查询的结果,如下所示:
ORs often slow down SQL queries. An alternative that may perform better is to union the result of separate queries, like so: