簡體   English   中英

僅在TSQL中滿足條件時才選擇列

[英]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位,並在CustomersProfileImageId添加一個具有適當外鍵的字段。 這樣,聯接將非常簡單明了,您將不必擔心維護該邏輯。

試試吧 :

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.

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