Thursday, 30 August 2018

MySQL Left Join Does Not Display the Lines of the Other Table

I have 2 tables. 1 table shows location information, and another shows wifi ssids and passwords for the location. These tables are joined by a column 'LocationID'. The reason for the 2 separate tables is so that I can keep a historical trail of ssids and passwords for a specific location.

My query is as follows:
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

What I need to do is obtain the most recent wifi ssid and passphrase from the table to show it with the corresponding locationID
I can do it with the following query:
SELECT * FROM LocationWiFi WHERE WiFiDate = (SELECT MAX(WiFiDate) FROM LocationWiFi) AND LocationID = xxxx

I am sure it isnt that hard, I just can not quite figure it out. Thanks in advance for any help!
EDIT...
Sorry for the confusion here everyone. let me try and be more clear. I have 1500+ entrys in location table. 2 entries in LocationWiFi table with the same locationid. I need the first query (the one with the join) to return all 1500+ rows, but only pull the wifi ssid and password with the max date. For the locations that do not have wifi ssid and passphrase, i simply want to show the column with a null value.
Again I apologize
SOLUTION
Hi Everyone,
I have solved this issue. For anyone who is having a similar solution, here is what worked for me.
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;


The following query is more efficient since it is not using a sub query:
SELECT *
FROM LocationWiFi
WHERE LocationID = xxxx
ORDER BY WiFiDate DESC
LIMIT 1

0 comments:

Post a Comment