Abfrage zwischen zwei verwandten Tabellen
Frage
Ich habe zwei Tische. Eine von ihnen (user_profile table) hat ein Feld mit dem Namen "user_profile_id" und die andere (user_friend table) enthält zwei Felder mit dem Namen "user_profile1_id" und "user_profile2_id", die FK zur ersten Tabelle sind.
Ich möchte überprüfen, ob es Benutzer in user_profile gibt, die weder in user_friend table sind, weder in user_profile1_id noch user_profile2_id.
Welche Abfrage soll ich verwenden?
BEARBEITEN:
CREATE TABLE user_profile (
--fields
)
CREATE TABLE user_friend (
user_profile1_id INT,
user_profile2_id INT
)
Lösung
Verwenden ein LEFT JOIN
und prüfen Sie nach Nullwerten. Etwas wie:
SELECT profile.* FROM user_profile profile
LEFT JOIN user_friend friend1 ON friend1.user_profile1_id = user_profile_id
LEFT JOIN user_friend friend2 ON friend2.user_profile2_id = user_profile_id
WHERE friend1.user_profile1_id IS NULL AND friend2.user_profile2_id IS NULL
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit dba.stackexchange