在连接sql时如何使用case

yebdmbv4  于 2021-06-20  发布在  Mysql
关注(0)|答案(5)|浏览(236)

如何编写这样的查询:

SELECT * FROM table1 t1
    case when @id=1 then
        join table2 t2 on t1.id=t2.t1id
    else
        join table3 t3 on t1.id=t3.t1id
    end t1

请帮忙

cvxl0en2

cvxl0en21#

您也可以在sqlserver中尝试使用动态sql

Declare @sql nvarchar(1000)
Declare @id int
Set @id = 2
Set @sql = 'select * from table t1'
if @id = 1
Begin
set @sql = @sql + ' join table2 t2 on t1.id=t2.t1id'
End
else 
Begin
set @sql = @sql + ' join table2 t3 on t1.id=t3.t1id'
End

Execute sp_executesql @sql
gjmwrych

gjmwrych2#

这有用吗。?

SELECT * FROM table1 t1
    LEFT join table2 t2 on t1.id=t2.t1id and @id=1
    Left join table3 t3 on t1.id=t3.t1id and @id<>1
wa7juj8i

wa7juj8i3#

你不能使用 CASE 就像那样。
只是使用 IF 选择查询作为一个整体,而不是像那样的片段,因为它在SQLServer中不起作用。

IF (@id = 1) BEGIN
    SELECT *
    FROM table1 AS t1
    INNER JOIN table2 AS t2 ON t1.id = t2.t1id
END
ELSE BEGIN
    SELECT *
    FROM table1 AS t1
    INNER JOIN table3 AS t3 ON t1.id = t3.t1id
END
eit6fx6z

eit6fx6z4#

尝试使用 OR . 而不是 CASE ```
SELECT * FROM table1 t1
JOIN table2 t2
on
(
(
@id=1
AND
t1.id=t2.t1id
)
OR
(
@id<>1
AND
t1.id=t2.t1id
)
)

w8rqjzmb

w8rqjzmb5#

下面的代码将得到与您所希望的相同的结果

SELECT * 
FROM table1 t1
    case when @id=1 then
LEFT JOIN table2 t2 on t1.id=t2.t1id
LEFT JOIN table2 t3 on t1.id=t3.t1id
WHERE (@id=1 AND t1.id=t2.t1id) 
 OR (@id<>1 AND t1.id=t3.t1id)

相关问题