gpt4 book ai didi

sql - 仅当先前的连接没有找到任何内容时才离开连接

转载 作者:行者123 更新时间:2023-11-29 13:41:00 26 4
gpt4 key购买 nike

我尽量把它放在最小的地方。

--

假设我有三个表,table1 table2 和 table3。所有这些表都有一列“organizationID”。我还有一个 table0,它以某种方式链接到所有这些。

“organizationID”有时在表1,有时在表2,有时在表3。

--

我正在做这样的事情:

SELECT coalesce(table1.organizationID,coalese(table2.organizationID,coalesce(table3.organizationID,0)))
FROM table0
LEFT JOIN table1 ON (some condition)
LEFT JOIN table2 ON (some condition)
LEFT JOIN table3 ON (some condition)

这行得通。它给了我我想要的。问题出在性能上。数据库始终执行所有三个连接,即使 table1 已经具有 orgaizationID。

--

我想将此选择修改为如下所示:

SELECT coalesce(table1.organizationID,coalese(table2.organizationID,coalesce(table3.organizationID,0)))
FROM table0
LEFT JOIN table1 ON (some condition)
LEFT JOIN table2 ON (some condition) AND table1.organizationID IS NULL
LEFT JOIN table3 ON (some condition) AND table2.organizationID IS NULL

问题在于它仍在执行所有连接,因此需要相同的时间来完成执行。

如果先前的连接成功,是否有任何方法可以阻止连接运行?

--

非常感谢。

--

编辑:table3 连接需要很多时间才能执行。我对此无能为力。所以我想避免在不需要时加入该表(也就是说,如果 table1 或 table2 已经有“organizationID”列)

最佳答案

查询将执行所有连接,因为可能需要所有连接——在不同的行上。

如果你真的想限制查找的次数,你可以使用case。像这样的东西:

SELECT . . ., 
(CASE WHEN EXISTS (SELECT 1
FROM table1 t1
WHERE t1.? = t0.? AND . . .
)
THEN (SELECT ?
FROM table1 t1
WHERE t1.? = t0.? AND . . .
)
WHEN EXISTS (SELECT 1
FROM table1 t2
WHERE t2.? = t0.? AND . . .
)
THEN (SELECT ?
FROM table2 t2
WHERE t2.? = t0.? AND . . .
)
. . .
END)
FROM table0;

但是,这不会加快查询速度。

相反,您可能只需要适当的索引来获得您真正想要的性能。

关于sql - 仅当先前的连接没有找到任何内容时才离开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55400212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com