如何在sql查询中对1=1执行条件交叉连接?
最初,我有一个如下所示的查询,在 1=1 上进行连接。 (它只是进行交叉联接,选择第一个表中的所有行和第二个表中的所有行,并显示为笛卡尔积,即具有所有可能性。)
SELECT * FROM Table1 t1
JOIN Table2 t2 ON 1=1
问题: 优化此查询在某种程度上,它只会显示特定 ID 的记录,如果我们没有 ID 或 ID 中有 NULL,那么它将显示与之前相同的结果 (1=1)。所以我写了下面的脚本。
Declare @T2id as int;
Set @T2id = 123;
SELECT * FROM Table1 t1
JOIN Table2 t2 ON
-- left side of join on statement
CASE
WHEN @T2id Is NULL
THEN 1
ELSE
t2.Id
END
=
-- right side of join on statement
CASE
WHEN @T2id Is NULL
THEN 1
ELSE
@T2id
END
任何人都可以确认,这好吗?或者我们可以有比这更好的方法吗?
Initially, I have a query like below, doing a join on 1=1. (It's simply doing a cross join, which selects all rows from the first table and all rows from the second table and shows as a cartesian product, i.e. with all possibilities.)
SELECT * FROM Table1 t1
JOIN Table2 t2 ON 1=1
Problem: Optimize this query in such a way, it will show only the records for a particular ID and if we don't have an ID or have a NULL in the ID then it will show the result same as previously(1=1). So I wrote the script below.
Declare @T2id as int;
Set @T2id = 123;
SELECT * FROM Table1 t1
JOIN Table2 t2 ON
-- left side of join on statement
CASE
WHEN @T2id Is NULL
THEN 1
ELSE
t2.Id
END
=
-- right side of join on statement
CASE
WHEN @T2id Is NULL
THEN 1
ELSE
@T2id
END
Can anyone confirm, is it good or we can have a better approach than this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你呈现交叉连接的方式是我以前从未见过的。
我的观点是,如果您只是:
至于问题,假设 SQL Server(您没有标记 RDBMS,但我从您的变量声明中猜测)您可能会考虑:
I think your way of presenting a cross-join is something I haven't seen before.
My view is it's simpler to read and understand if you just:
As for the question, assuming SQL Server (you didn't tag the RDBMS, but I guess from your variable declaration) you might consider: