[英]How to select a column only if condition is met in TSQL
我有两张桌子。 客户和图像。
我加入这些,并且仅当图像是个人资料图片时,才从“图像”表中选择一个图像ID。
但是,如果用户有几张图片,但个人资料图片仅在图片中,我仍然会和同一用户返回几行。
我的代码:
SELECT DISTINCT c.Id, c.Name, c.LastName, c.Email, c.MobilePhoneNumber,
(SELECT CASE WHEN im.Isprofile = 1 THEN im.Id END) AS ImageId,
im.ContentType
FROM Customers c
JOIN Images im ON im.CustomerId = c.Id
“ CASE WHEN”显然是错误的,这感觉太简单了,但是我已经有一段时间了,无法弄清。
由于ImageId为null,因此我只想在此显示一行
SELECT DISTINCT c.Id,
c.Name,
c.LastName,
c.Email,
c.MobilePhoneNumber,
(im.Id) AS ImageId, im.ContentType FROM Customers c
LEFT JOIN Images im ON im.CustomerId = c.Id and im.Isprofile = 1
希望这可以帮助
使用OUTER APPLY
:
SELECT c.Id,
c.Name,
c.LastName,
c.Email,
c.MobilePhoneNumber,
im.ID AS ImageID,
im.ContentType
FROM Customers c
OUTER APPLY(SELECT TOP 1 ID, ContentType FROM Images im
WHERE im.CustomerId = c.Id AND im.Isprofile = 1) im
这取决于您的实现,但是从长远来看,这可能会让您受益。 这与我在此处所做的工作相同,但是使用CTE代替。
WITH ProfilePictures AS (
SELECT ID, ContentType, CustomerId
FROM Images i
WHERE i.IsProfile = 1
)
SELECT c.Id, c.Name, c.LastName, c.Email, c.MobilePhoneNumber, im.Id AS ImageId, im.ContentType
FROM Customers c
LEFT OUTER JOIN ProfilePictures im ON im.CustomerId = c.Id
此实现假定每个客户都有正好为零或一个标记为IsProfile = 1
图像。
需要明确的是,如果您只看一次或两次此逻辑,这是过大的。 我只是想将客户与他们的照片联系起来可能是您要做的很多事情,在这种情况下,抽象出逻辑可能会派上用场。
对于我来说,如果我的解释正确,并且肯定由您决定,那么我很想删除IsProfile
位,并在Customers
为ProfileImageId
添加一个具有适当外键的字段。 这样,联接将非常简单明了,您将不必担心维护该逻辑。
试试吧 :
SELECT
DISTINCT cust.Id
,cust.Name
,cust.LastName
,cust.Email
,cust.MobilePhoneNumber
,img.Id AS ImageId
,img.ContentType
FROM Customers as cust
LEFT OUTER JOIN Images as img ON img.CustomerId = cust.Id and img.Isprofile = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.