簡體   English   中英

在SQL之間的聯接之間如何使用情況

[英]How can use case when in between join in Sql

如何編寫這樣的查詢:

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

請幫忙

這有幫助嗎?

    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

嘗試使用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
            )
        )

下面的代碼將與您期望的結果相同

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)

您不能那樣使用CASE

只需使用IF選擇查詢整體,而不要像這樣分段,因為它不能在SQL Server中使用。

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

您也可以在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      

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM