2013-04-18 4 views
10

Diese Abfrage funktioniert:Fehler bei der außer in einer Abfrage mit

mysql> SELECT s.sno FROM students s; 
+------+ 
| sno | 
+------+ 
| 1 | 
| 2 | 
| 3 | 
| 4 | 
| 5 |  
| 6 |  
| 7 | 
| 8 | 
| 9 | 
| 10 | 
+------+ 
10 rows in set (0.00 sec) 

Diese Abfrage funktioniert auch:

mysql> SELECT t.sno FROM take t WHERE t.cno = 'CS112'; 
+------+ 
| sno | 
+------+ 
| 1 | 
| 2 | 
| 3 | 
| 4 | 
+------+ 
4 rows in set (0.00 sec) 

aber diese Abfrage:

SELECT s.sno FROM students s  
EXCEPT  
SELECT t.sno FROM take t WHERE t.cno = 'CS112'; 

mit dem Fehler fehlschlägt:

mysql> SELECT s.sno FROM students s 
    -> EXCEPT 
    -> SELECT t.sno FROM take t WHERE t.cno = 'CS112'; 
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use n 
ear 'EXCEPT 
SELECT t.sno FROM take t WHERE t.cno = 'CS112'' at line 2 

Was mache ich hier falsch?

Antwort

14

Ich glaube nicht, MySQL unterstützt EXCEPT-Syntax. Versuchen Sie es mit NOT IN oder ein LEFT JOIN:

SELECT s.sno 
FROM students s  
WHERE s.sno NOT IN 
(
    SELECT t.sno 
    FROM take t 
    WHERE t.cno = 'CS112' 
); 

ODER

SELECT s.sno 
FROM students s  
    LEFT JOIN take t ON s.sno = t.sno 
WHERE IFNULL(t.cno, '') != 'CS112' 

UPDATE

verspottete ich Ihre Daten als solche und es gibt richtig 5 bis 10:

create temporary table temp_students (sno int) 

insert into temp_students values (1) 
insert into temp_students values (2) 
insert into temp_students values (3) 
insert into temp_students values (4) 
insert into temp_students values (5) 
insert into temp_students values (6) 
insert into temp_students values (7) 
insert into temp_students values (8) 
insert into temp_students values (9) 
insert into temp_students values (10) 

create temporary table temp_take (sno int, cno varchar(50)) 

insert into temp_take values (1, 'CS112') 
insert into temp_take values (2, 'CS112') 
insert into temp_take values (3, 'CS112') 
insert into temp_take values (4, 'CS112') 

SELECT s.sno 
FROM temp_students s  
     LEFT JOIN temp_take t ON s.sno = t.sno 
WHERE IFNULL(t.cno, '') != 'CS112' 
+1

Sie sind recht nicht 'EXCEPT' unterstützen. Ihre Alternative liefert jedoch nicht das richtige Ergebnis. – Cratylus

+0

Sie suchen Sno von 5-10 zurückgegeben, richtig? – McCee

+0

Die von Ihnen gepostete Abfrage gibt das nicht zurück. – Cratylus

6

Abfrage:

SQLFIDDLEExample

SELECT s.sno 
FROM students s 
WHERE NOT EXISTS (SELECT 0 
        FROM take t 
        WHERE t.sno = s.sno 
        AND t.cno = 'CS112') 
+0

Dies ist die beste Antwort, da es auch auf mehreren Feldern funktioniert –

Verwandte Themen