在SQL之间的联接之间如何使用情况

时间:2018-08-29 05:12:10

标签: mysql sql sql-server

如何编写这样的查询:

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

请帮助

5 个答案:

答案 0 :(得分:3)

这有帮助吗??

    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

答案 1 :(得分: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
            )
        )

答案 2 :(得分:0)

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

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)

答案 3 :(得分:0)

您不能像这样使用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

答案 4 :(得分:0)

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