[英]How to add condition to left join on existing the row in another table
我有這個查詢:
SELECT
p.id,
COUNT(a.id) accounts,
sum(case when a.state = '0' then 1 else 0 end) active_accounts
FROM Person p
LEFT JOIN Account a
ON a.person_id = p.id ADN
WHERE p.id = 1
GROUP BY p.id;
如何通過將bank
表上的account.bank_name = bank.name
為accounts
和active_accounts
值來添加具有有效bank_name
的帳戶條件?
這是數據庫方案:
Person (
id
)
Account (
id
person_id
state -- 0 - active, 1 - closed
bank_name
)
Bank (
id,
name
)
如果“ Account
bank_name
不正確(“ Bank
表中沒有這樣的行),則不應計算在內。
諸如此類,將左連接添加到bank表和where子句以檢查name是否為null:
SELECT
p.id,
COUNT(a.id) accounts,
sum(case when a.state = '0' then 1 else 0 end) active_accounts
FROM Person p
LEFT JOIN Account a ON
a.person_id = p.id
LEFT JOIN bank b ON
a.bank_name = b.name
WHERE p.id = 1 and
b.name is not null
GROUP BY p.id
參見http://sqlfiddle.com/#!9/2b43b3/3
SELECT
p.id,
COUNT(a.id) accounts,
sum(case when a.state = '0' then 1 else 0 end) active_accounts
FROM Person p
LEFT JOIN Account a ON a.person_id = p.id
INNER JOIN Bank on a.bank_name = Bank.name
WHERE p.id = 1
GROUP BY p.id;
使用外鍵,較精通的ddl會像這樣
create table person (
id int unique not null
);
create table bank (
id int unique not null,
name nvarchar(10)
);
create table account (
id int unique not null,
person_id int,
state bit,
bank_id int,
FOREIGN KEY (bank_id) REFERENCES bank(id),
FOREIGN KEY (person_id) REFERENCES person(id)
);
Insert into person values (1), (2);
insert into bank VALUES (1, "B1"),(2, "B2");
insert into account values (1,1,1,1), (2,1,0,1),(3,1,1,1),(4,2,1,1);
這種DDL將允許您擁有沒有銀行的accounts
( bank_id
== null)或具有有效的bank_ids
accounts
-DB會為您處理-不需要在ncharchar()s上進行不安全的聯接-如果以下情況可能會出錯您提交一些尾隨/前導空格
CTE的另一種方式(如果您的數據庫支持):
with account_valid as (
select
a.*
from
Account a
inner join bank b on
a.bank_name = b.name
)
select
p.id,
count(a.id) accounts,
sum(case when a.state = '0' then 1 else 0 end) active_accounts
from
Person p
left join account_valid a ON
a.person_id = p.id ADN
where
p.id = 1 -- condition just for test
group by
p.id
或使用嵌套查詢:
select
p.id,
count(a.id) accounts,
sum(case when a.state = '0' then 1 else 0 end) active_accounts
from
Person p
left join (
select
a.*
from
Account a
inner join bank b on
a.bank_name = b.name
) account_valid a ON
a.person_id = p.id ADN
where
p.id = 1 -- condition just for test
group by
p.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.