使用WHERE

时间:2017-10-12 20:00:50

标签: mysql sql join left-join

我有以下3个表格:

Clients AS c
--------
ClientID,
ClientGUID,
InitializationDate,
LastCheckin

ClientServices AS cs
---------------
ClientID,
ServiceID,
Status,
Version

Services AS s
---------
ServiceID,
Name,
Description

我需要构建一个查询,它会给我以下结果:

s.Name, cs.Version

我需要它作为左连接,因为我希望显示所有服务,无论该服务是否在ClientServices中。在这种情况下,所选版本将仅显示为NULL

我尝试过一些简单的连接,但我使用的LEFT JOINJOIN的每个组合只会导致属于该客户端的ClientServices出现。一个例子:

SELECT    s.`Name`, 
          cs.`Version` 
FROM      `Services` s LEFT JOIN ClientServices cs ON 
          s.`ServiceID` = cs.`ServiceID` 
          JOIN Clients c ON 
          cs.`ClientID` = c.`ClientID` 
WHERE     `ClientGUID`='thisisanewguid'

我终于可以通过此查询获得所需的结果:

SELECT    s.`Name`, 
          cs.`Version` 
FROM      `Services` s LEFT JOIN ClientServices cs 
          ON s.`ServiceID` = cs.`ServiceID` 
WHERE     cs.ClientID = (
                            SELECT    ClientID 
                            FROM      Clients 
                            WHERE     ClientGUID='thisisanewguid'
                        ) 
OR        cs.ClientID IS NULL

但我觉得它有点" hacky"。有没有更好的方法来获得相同的结果集,但没有在一个查询中进行多次选择? (最好只有连接,但我不确定这是否可能)

示例数据集:

客户:

ClientID,         ClientGUID, InitializationDate, LastCheckin
       1, 'xxxxxxxxxxxxxxxx',         10/10/2017,  10/12/2017
       2,   'thisisanewguid',         05/23/2017,  10/12/2017

ClientServices:

ClientID, ServiceID, Status, Version
       1,         1,      1,   '0.1'
       2,         1,      1,   '0.1'
       2,         2,      1,   '0.2'

服务

ServiceID,        Name,                              Description
        1, InITManager, 'Manages and updates all InIT services.'
        2,     InITIAM,     'InIT's Inventory/Asset Management.'
        3, InITTesting,                                'testing'

所需的结果集WHERE ClientGUID =' thisisanewguid'

       Name, Version
InITManager,   '0.1'
    InITIAM,   '0.2'
InITTesting,    NULL

2 个答案:

答案 0 :(得分:2)

对于obatin您显示的结果您可以使用左表连接左连接没有where子句的列涉及id left join

SELECT    s.`Name`, 
          cs.`Version` 
FROM      `Services` s 
LEFT JOIN ClientServices cs ON   s.`ServiceID` = cs.`ServiceID` 
LEFT JOIN Clients c ON c.ClientID = cs.ClientID  AND c.`ClientGUID`='thisisanewguid'

答案 1 :(得分:0)

您好,请尝试以下查询

SELECT cs.Version, s.Name 
FROM ClientServices cs
RIGHT JOIN Clients c ON c.ClientID = cs.ClientID
RIGHT JOIN Services s ON s.ServiceID = cs.ServiceID