4

我需要将以下两个工作查询转换为一个查询,但是由于各种原因,我尝试的所有内容都死在了我身上。我的最终结果是尝试列出手头上的所有软件,并显示为正在查询的特定 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 表(多对多)

------------------
| 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。

4

4 回答 4

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:也许不是最有效/最漂亮的,但它有效

于 2012-09-23T02:46:37.477 回答
1

根据您的要求,这将为您提供正确的结果:

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
    left join device
        on device_software.d_id = device.d_id
            and device.d_id = 1

只是注意:我更喜欢将主键作为表中的第一列。我也建议用复数命名你的表(设备)

于 2012-09-23T05:23:38.500 回答
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
;
于 2012-09-23T15:58:27.993 回答
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`
于 2012-09-23T02:46:12.343 回答