我来自程序编程背景,最近用我的新工作编写了TSQL。我的思维方式仍在考虑用if条件编写查询。如果没有条件,如何避免跟随查询。
DECLARE @NumAddress INT
SELECT
@NumAddress = COUNT(*)
FROM Address
WHERE UserID = 1001
IF @NumAddress > 0
BEGIN
SELECT
u.FullName, a.Address AS Address
FROM
Users u
JOIN Address a ON a.UserID = u.UserID
WHERE
u.UserId = 1000
END
ELSE
BEGIN
SELECT
u.FullName, NULL AS Address
FROM
Users u
WHERE
u.UserId = 1000
END
注意:我的示例查询是我实际查询的简化示例。所以请忽略这个并给我一个例子,这样我怎么能避免像这样的IF条件。提前谢谢。
答案 0 :(得分:4)
在这种特定情况下,您最好使用left
join:
select
u.FullName,
a.Address
from
users u
left join address a on
a.userid = u.userid
where
u.userid = 1000
如果找不到匹配项,则会返回null
列的所有address
。
但是,要从更广泛的意义上回答您的问题,您可以在查询中使用case
statement,以避免必须拥有整个whoopla:
select
u.fullname,
case
when (select count(*) from address where userid = u.userid) > 0 then 1
else 0
end as AddressSupplied
from
users u
where
userid = 1000
case
是SQL中的switch
语句,因此您可以这样做:
case col_name
when 'Val1' then 'Yup'
when 'Val2' then 'Well...'
when 'Val3' then 'Nope.'
else 'What now?'
end
这将检查每行上的col_name
列,如果它是指定值之一,它将返回正确的then
。因此,示例查询和结果集为:
select
col_name,
case col_name
when 'Val1' then 'Yup'
when 'Val2' then 'Well...'
when 'Val3' then 'Nope.'
else 'What now?'
end as some_col
from
tableA
--------------------
col_name some_val
--------------------
Val1 Yup
Val2 Well...
Val1 Yup
Val4 What now?
Val3 Nope.
这也适用于where
子句,这对于半条件查询非常方便:
where
userid = case when @somevar > 0 then 1000 else 1001 end
答案 1 :(得分:3)
我假设1000/1001之间的差异是一个错字。外部联接应该可以解决您的问题。如果没有地址,您仍然会获得带有空地址的'FullName`。
SELECT
u.FullName, a.Address AS Address
FROM
Users u
LEFT OUTER JOIN Address a ON a.UserID = u.UserID
WHERE
u.UserId = 1000
答案 2 :(得分:1)
您可以使用左连接
SELECT
u.FullName, a.Address AS Address
FROM
Users u
LEFT JOIN Address a ON a.UserID = u.UserID
WHERE
u.UserId = 1000
答案 3 :(得分:1)
外部联接可以解决问题。
SELECT u.FullName, a.Address
FROM Users u
LEFT OUTER JOIN Address a ON a.UserId = u.UserId
WHERE UserId = 1000
答案 4 :(得分:0)
当然左连接是这个问题的正确答案,顺便提一下在TSQL中你可以用更简单的方式使用左连接,在你的情况下使用= *
SELECT u.FullName, a.Address FROM Users u, Address a WHERE u.UserId =* a.UserId and u.UserId = 1000
Peoples们纠正我:这个语法在MSSQL中被贬低(我认为)并且应该永远不要在生产项目中使用:)
顺便说一下,你可以在这里使用subselect,但不太习惯的方式
SELECT u.FullName, (select a.Address FROM Address a where a.UserId = u.UserId) FROM Users u WHERE u.UserId = 1000