我需要将以下两个工作查询转换为单个查询但所有内容 我试着因为各种原因而死在我身上。我的最终结果是尝试列出所有 现有软件,并显示已安装的软件以及未针对要查询的特定PC安装的软件。对于已安装的软件,请列出名称,否则显示名称为NULL。我在where子句中尝试了一些子选择语句,它给了我一个没有错误的结果,但没有给出正确的结果。任何帮助表示赞赏。
qry1
SELECT device_software.sw_id
FROM Software_device LEFT JOIN Device ON Software_device.d_id = Device.d_id
WHERE Device.d_id = 1;
qry2
SELECT Software.name, Software.sw_id, qry1.sw_id
FROM software LEFT JOIN qry1 ON software.sw_id = qry1.sw_id;
设备表
------------------
| name | d_id |
------------------
| PC1 | 1 |
| PC2 | 2 |
| PC3 | 3 |
------------------
软件表
------------------
| name | sw_id |
------------------
| SW_a | A |
| SW_b | B |
| SW_c | C |
| SW_d | D |
------------------
Software_Device Table(多对多)
------------------
| d_id | sw_id |
------------------
| 1 | A |
| 1 | B |
| 2 | A |
| 2 | B |
| 2 | C |
------------------
结果我正在寻找...... (PC1上已安装和未安装的软件)
---------------------------------
| Sotfware | pc_id | name |
---------------------------------
| SW_a | 1 | PC1 |
| SW_b | 1 | PC1 |
| SW_c | NULL | NULL |
| SW_d | NULL | NULL |
---------------------------------
我列出了mysql和sql标签,因为我认为这不重要,但是如果它确实存在,我正在使用mysql。
答案 0 :(得分:1)
SELECT
s.name AS software,
IF((SELECT COUNT(sw.d_id) FROM software_device sw WHERE sw.sw_id = s.sw_id AND d_id = 1) > 0, 1, NULL) AS pc_id,
(SELECT d.name FROM device d INNER JOIN software_device sw ON d.d_id = sw.d_id WHERE sw.sw_id = s.sw_id AND d.d_id = 1) AS name
FROM
software s
ORDER BY s.name
编辑2:也许不是最有效/最美丽的,但它有效
答案 1 :(得分:1)
如果RomanKonz的答案肯定很接近,只需将“where”移动到“on”,让左连接正常工作。
select software.name as Software,
device.d_id as pc_id,
device.name as name
from software
left join device_software
on device_software.sw_id = software.sw_id
and **device_software**.d_id = 1
left join device
on device_software.d_id = device.d_id
;
答案 2 :(得分:0)
以下内容可以满足您的需求:
select s.`name` as `Software`, d.`d_id`, d.`name` as `Device`
from software s
left outer join software_device sd
on sd.`sw_id` = s.`sw_id` and sd.`d_id` = 1
left outer join device d using (`d_id`)
order by s.`name`