在一个租赁管理数据库中,我有三个表,一个表包含我的物品库存,一个表用于预订这些物品,另一个表存储所有项目:
库存
IdStockType Number Caption Inventory
1 100001 Monitor 10
2 100002 Keyboard 25
3 100003 Notebook 05
4 100004 Desktop 07
预订
id IdStockType RentalPrice Factor Project
1 2 15 5 1
2 2 03 2 2
3 4 90 3 2
项目
id Caption startDate endDate
1 Festival 2019 2019-03-01 2019-03-05
2 Kick-Off ABC 2019-04-15 2019-04-17
3 Big Conference 2019-04-16 2019-04-16
现在,我想编写一个查询,向我提供有关预订和项目信息的全部库存。如果没有租借物品,则无论如何都应列出该物品。如果是租用的,则应仅与预订和项目信息一起列出。因此可以多次出现:
IdStockType Number Factor Inventory Article RentalPrice Project
1 100001 (NULL) 10 Monitor (NULL) (NULL)
2 100002 5 25 Keyboard 15 Festival 2019
2 100002 2 25 Keyboard 03 Kick-Off ABC
3 100003 (NULL) 05 Notebook (NULL) (NULL)
4 100004 3 07 Desktop 90 Kick-Off ABC
现在我的查询有问题:
SELECT * FROM (
SELECT
p.IdStockType,
p.Number,
o.Factor,
p.Inventory,
p.Caption AS Article,
q.Caption AS Project
FROM
stock p,
bookings o,
projects q
WHERE
p.IdStockType = o.IdStockType AND
o.Project = q.id
) AS u
RIGHT JOIN (SELECT
r.IdStockType,
r.Number,
NULL,
NULL,
r.Caption AS Article,
NULL
FROM
stock r) d ON d.IdStockType = u.IdStockType;
输出的行数似乎是正确的,但是由于将一致的列添加为新列,因此信息的组合很奇怪。
有人可以帮助我查询吗?
谢谢。
问候 拉斯
答案 0 :(得分:1)
select *
from Stock stock
left join (
select
*
from
Bookings bookings
join Projects projects
on bookings.Project = projects.Id
) bookingProjects on stock.IdStockType = bookingProjects.IdStockType