我有以下 2 個表:
表格1priceList
| ID | 貨幣ID |
|---|---|
| 3 | DF10CCE |
表 2 priceListItems
| ID | 價格表ID | 產品 |
|---|---|---|
| 1 | 3 | 桌子 |
我想在 SQL 中撰寫一條陳述句,如果 priceList 中有專案,則回傳布林值(0 或 1),并根據它們的 ID 列與 priceListItems 進行比較(對于表 A:ID = 3,對于表 B:priceListID = 3 )
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
一個簡單的左連接和一個案例可以解決這個問題
select pl.*,
convert(bit, case when pli.ID is null then 0 else 1 end) as HasItems
from PriceList pl
left join PriceListItem pli on pl.ID = pli.priceListID
注意sql server中沒有booleantype,最接近的是bittype,只能是0/1,很多軟體會顯示為false/true
單擊此鏈接以查看查詢作業
結果是
| ID | 貨幣id | 有物品 |
|---|---|---|
| 3 | DF10DDE | 真的 |
| 4 | 廢話 | 錯誤的 |
uj5u.com熱心網友回復:
嘗試
WITH CTE AS
(
SELECT a.ID FROM priceList a inner JOIN priceListItems b
ON a.ID = b.priceListID
)
SELECT
CASE WHEN EXISTS (SELECT 1 from CTE) then 1 ELSE 0 END as bool
uj5u.com熱心網友回復:
您可以使用外部連接:
select pl.*,
(case when pli.priceListID is not null then 1 else 0 end) as flag
from priceList pl left join
priceListItems pli
on pli.priceListID = pl.id
uj5u.com熱心網友回復:
你的資料
declare @priceList table (
ID int NOT NULL
,CurrencyID VARCHAR(70) NOT NULL
);
INSERT INTO @priceList
(ID,CurrencyID) VALUES
(3,'DF10CCE');
declare @priceListItems table (
ID int NOT NULL
,priceListID int NOT NULL
,Product VARCHAR(40) NOT NULL
);
INSERT INTO @priceListItems
(ID,priceListID,Product) VALUES
(1,3,'DESK');
用于full join區分存在。
SELECT Iif(pl.id IS NULL, 0, 1)
FROM @priceListItems pli
FULL JOIN @priceList pl
ON pl.id = pli.pricelistid
-- where pl.id =3 --where condition
uj5u.com熱心網友回復:
請注意,簡單的左連接是不夠的,因為(我假設)查詢應該只回傳每個 priceList 記錄的一條記錄。嘗試:
select
pl.ID,
case
when pli.priceListID is null then 0
else 1
end as HasItems
from
priceList as pl
left join (select distinct priceListID from priceListItems) as pli on pli.priceListID = pl.ID
;
uj5u.com熱心網友回復:
select coalesce(max(1), 0)
from priceList p inner join priceListItems pi on pi.priceListID = p.ID
where p.ID = X
考慮到關系,內部連接甚至可能是多余的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/466143.html
