根据另一个 table 值获取具有名称或 null 的项目列表
Get list of items with name or null based on another table values
我有这样的模式:
现在我想写查询which returns me list of items with borrower name only if book is borrowed now,否则借款人姓名应该为空。
我觉得这应该很容易;我一直在尝试使用多个连接和 NULL 条件,但我仍然无法得到我想要的。也许我应该更改架构?
SELECT items.*, borrowers.first_name, borrowers.last_name
FROM items
LEFT JOIN borrows ON borrows.item_id = items.id AND return_date IS NULL
LEFT JOIN borrowers ON borrowers.id = borrows.borrower_id
像这样应该可以解决问题:
select Items.title,
case
when b1.return_date is null then b2.first_name || ' ' || b2.last_name
else null
end as 'Borrower name'
from Items i
join Borrows b1 on b1.item_id = i.id
join Borrowers b2 on b2.id = b1.borrower_id
这总是选择项目的标题,并连接借款人的 first_name 和 last_name,但前提是 return_date 为空。否则,null 被选为 'Borrower name'
您可以在 Borrowers
table 上使用 LEFT OUTER JOIN
来执行此操作,条件是 return_date
IS NULL
.
这应该适合你:
Select I.*,
B.First_Name,
B.Last_Name
From Borrows W
Join Items I On W.item_id = I.Id
Left Join Borrowers B On W.borrower_id = B.id
And W.return_date Is Null
我有这样的模式:
现在我想写查询which returns me list of items with borrower name only if book is borrowed now,否则借款人姓名应该为空。 我觉得这应该很容易;我一直在尝试使用多个连接和 NULL 条件,但我仍然无法得到我想要的。也许我应该更改架构?
SELECT items.*, borrowers.first_name, borrowers.last_name
FROM items
LEFT JOIN borrows ON borrows.item_id = items.id AND return_date IS NULL
LEFT JOIN borrowers ON borrowers.id = borrows.borrower_id
像这样应该可以解决问题:
select Items.title,
case
when b1.return_date is null then b2.first_name || ' ' || b2.last_name
else null
end as 'Borrower name'
from Items i
join Borrows b1 on b1.item_id = i.id
join Borrowers b2 on b2.id = b1.borrower_id
这总是选择项目的标题,并连接借款人的 first_name 和 last_name,但前提是 return_date 为空。否则,null 被选为 'Borrower name'
您可以在 Borrowers
table 上使用 LEFT OUTER JOIN
来执行此操作,条件是 return_date
IS NULL
.
这应该适合你:
Select I.*,
B.First_Name,
B.Last_Name
From Borrows W
Join Items I On W.item_id = I.Id
Left Join Borrowers B On W.borrower_id = B.id
And W.return_date Is Null