2017-01-25 6 views
0

Ich habe zwei Tabelle. fisrt ist "tab_task"Ich möchte die Zeilen auswählen, die nicht folgen, wo Bedingung oder "außer wo Bedingung"

task_id| task_name | created_by | status 
    ------------------------------------------- 
    1 | task1  | aarav | 1 
    2 | task2  | rahul | 0 
    3 | task3  | aarav | 0 
    4 | task4  | jasmin | 0 
    5 | task5  | yamini | 1 
    6 | task6  | priyanka | 0 
    7 | task7  | manish | 1 
    8 | task8  | aarav | 1 

und die zweite Tabelle ist "tab_user"

user_id| txt_full_name| 
    ------------------------- 
    1 | aarav  | 
    2 | rahul  | 
    3 | yamini  | 
    4 | jasmin  |  
    5 | manish  | 
    6 | priyanka | 

SELECT created_by from tab_task where status='1' jetzt haben wir vier Reihen "Aarav, yamini, manish und Aarav".

Jetzt möchte ich den "txt_full_name" von "tab_user" holen, wobei "txt_full_name" nicht gleich "tab_task's created_by" ist. Ich meine, ich möchte holen: rahul, jasmin, priyanka von "tab_user".

+0

Grob: Wählen Sie x. * Von x links verbinden y auf y.etwas = x.etwas und y.otherthing =? WHERE y.primary_key IS NULL – Strawberry

Antwort

2

Eine einfache Lösung:

SELECT txt_full_name FROM tab_user 
    WHERE txt_full_name NOT IN (SELECT created_by from tab_task where status='1') 

(beachten Sie, dass das oben die created_by Spalte annimmt, ist NOT NULL, sonst wird die Abfrage keine Zeilen zurück, da Vergleich mit NULL Ausbeuten UNKNOWN-fiddle - doesn't work with NULL data).

+0

Was passiert, wenn eine created_by, die NULL ist, von der Unterabfrage zurückgegeben wird? – jarlh

+0

@jarlh good catch - http://sqlfiddle.com/#!9/09b01/1 –

+2

Deshalb mache ich normalerweise 'NOT EXISTS' stattdessen. Weniger überraschendes Ergebnis, wenn plötzlich ein NULL-Wert angezeigt wird. – jarlh

0

Versuchen Sie, die Tabellen zu verknüpfen, wählen Sie dann die null Zeilen:

SELECT txt_full_name FROM tab_user 
LEFT OUTER JOIN 
(
    SELECT created_by from tab_task where status='1' 
)tbStat 
ON created_by = txt_full_name 
WHERE created_by IS NULL 
1

Neben @Jiri Tousek der IN Lösung, können Sie auch JOIN verwenden, EXISTS Syntax:

select u.txt_full_name 
from tab_user u 
left join tab_task t 
on u.txt_full_name = t.created_by 
and t.status = '1' 
where t.created_by is null; 

Oder

select u.txt_full_name 
from tab_user u 
where not exists(
    select 1 from tab_task t where u.txt_full_name = t.created_by and t.status = '1' 
); 

und siehe demo sie e.

Verwandte Themen