Ich versuche, eine Liste von company_id
's zu erhalten, die keine Notizen auf Unternehmensebene haben. Die Firma kann jedoch Notizen auf Standortebene haben.MySQL Select Distinct mit linker Join?
company
-------------------------
company_id name deleted
1 Foo 0
2 Bar 0
3 Baz 0
location
-----------------------
location_id company_id
6 1
7 2
8 3
note
-----------------------------------------
note_id company_id location_id deleted
10 2 6 0 // location-level note
11 1 7 0 // location-level note
12 null 8 0 // location-level note
13 2 null 0 // company-level note
Ich würde meine Ergebnistabelle dies sein will:
company_id name
1 Foo
3 Baz
aktualisiert
Foo
/company_id = 1
keine Unternehmensebene zur Kenntnis, weil die Note auch ein location_id
hat, was es zu einer Notiz auf Standort-Ebene macht. Notizen auf Unternehmensebene sind Notizen, die nur auf eine Firma (und nicht auf einen Standort) verweisen.
Ende des Update
Ich habe versucht, so etwas wie dies zu tun, aber es gibt eine leere Menge, so dass ich bin mir nicht sicher, ob es funktioniert und es gibt keine Unternehmen ohne Unternehmensebene Notizen oder wenn ich etwas falsch mache.
SELECT DISTINCT
c.company_id,
c.name
FROM company AS c
LEFT JOIN note AS n
ON c.company_id = n.company_id
WHERE
c.deleted = 0 AND
n.deleted = 0 AND
n.location_id IS NOT NULL AND
n.location_id != 0 AND
c.company_id = (SELECT MAX(company_id) FROM company)
Überarbeitete akzeptierte Antwort von Mike
SELECT
company_id,
name
FROM company
WHERE
deleted = 0 AND
company_id NOT IN (
SELECT DISTINCT
c.company_id
FROM company AS c
INNER JOIN note AS n
ON c.company_id = n.company_id
WHERE (
n.deleted = 0 AND
(n.location_id IS NULL OR
n.location_id = 0)
)
);
'Deleted' Spalte fehlt in Beispieldaten, und diese Bedingungen' n.deleted = 0 und n.location_id IST NOT NULL UND n.location_id! = 0 'schaltet die 'Linke join' zu' Inner join ' –
' c.company_id = (SELECT MAX (Firma_ID) FROM Firma) 'Dies wird sicherstellen, dass das Ergebnis hat nur eine' company_id' –
@Prdp aktualisierte Frage zu enthalten gelöschte Spalten. Wie verhindere ich, dass die Linke zu einem Inner Join wird und gleichzeitig nur nach Firmennotizen gesucht wird? – GreeKatrina