MySQL Left Join不显示另一个表中的行

时间:2013-11-09 23:37:31

标签: mysql sql inner-join

我有2张桌子。 1表显示位置信息,另一个表显示该位置的wifi ssids和密码。这些表由“LocationID”列连接。 2个单独表的原因是我可以保留特定位置的ssids和密码的历史记录。

我的查询如下:

SELECT Location.LocationID,
    Location.SystemName,
    Location.SiteNameLocation,
    Location.SiteAddress1,
    Location.SiteAddress2,
    Location.SiteCity,
    Location.SiteProvince,
    Location.SitePostalCode,
    Location.ContactName,
    Location.ContactPhone, 
    Location.ContactEmail,
    Location.ID1POC,
    Location.ID2District,
    Location.SiteLocationHours,
    LocationWiFi.WiFiSSID,
    LocationWiFi.WiFiPassphrase,
    LocationWiFi.WiFiDate
    FROM Location
    LEFT JOIN LocationWiFi ON LocationWiFi.LocationID = Location.LocationID

我需要做的是从表中获取最新的wifi ssid和passphrase以显示相应的locationID

我可以使用以下查询来完成:

SELECT * FROM LocationWiFi WHERE WiFiDate = (SELECT MAX(WiFiDate) FROM LocationWiFi) AND LocationID = xxxx

我确信这不是很难,我只是无法弄明白。在此先感谢您的帮助!

编辑...

对不起大家的困惑。让我试着更清楚。我在位置表中有1500多个托管。 LocationWiFi表中的2个条目具有相同的locationid。我需要第一个查询(带连接的查询)返回所有1500多行,但只用最大日期拉wifi ssid和密码。对于没有wifi ssid和passphrase的位置,我只想显示一个空值的列。

我再次道歉

大家好,

我已经解决了这个问题。对于任何有类似解决方案的人来说,这对我有用。

SELECT Location.LocationID,
    Location.SystemName,
    Location.SiteNameLocation,
    Location.SiteAddress1,
    Location.SiteAddress2,
    Location.SiteCity,
    Location.SiteProvince,
    Location.SitePostalCode,
    Location.ContactName,
    Location.ContactPhone, 
    Location.ContactEmail,
    Location.ID1POC,
    Location.ID2District,
    Location.SiteLocationHours,
    a.WiFiSSID,
    a.WiFiPassphrase
    FROM Location
    LEFT JOIN(
SELECT LocationWiFi.WiFiSSID,
           LocationWiFi.WiFiPassphrase,
           LocationWiFi.LocationID
FROM LocationWiFi
WHERE LocationWiFi.WiFiDate = (SELECT MAX(WiFiDate) FROM LocationWiFi)
    ) AS a
    ON a.LocationID = Location.LocationID;

2 个答案:

答案 0 :(得分:0)

以下查询更有效,因为它没有使用子查询:

SELECT * 
FROM LocationWiFi 
WHERE LocationID = xxxx
ORDER BY WiFiDate DESC
LIMIT 1

答案 1 :(得分:0)

你拥有所需的一切,只需将它们放在一起:

SELECT l.*, lw.*
FROM Location l
JOIN LocationWifi lw ON l.locationId= lw.locationId
WHERE lw.WiFiDate = (
  SELECT MAX(WiFiDate)
  FROM locationWifi
  WHERE locationId = l.locationId
);

这是每行的子查询,但我认为没有任何好办法。

SQLFiddle:http://sqlfiddle.com/#!2/350ac/1