2016-06-01 72 views
0
SELECT DISTINCT CONCAT('TOTAL NUMBER OF LEGS IN A TRIP NUMBER ', T1.TNUM, ' IS NOT EQUAL TO THE LARGEST NUMBER OF LEG IN THE TRIP') AS 'ERR' 
FROM TRIPLEG T1 
WHERE MAX(T1.LEGNUM) = (SELECT COUNT(T2.TNUM) 
        FROM TRIPLEG 
        WHERE T1.TNUM = T2.TNUM); 

與我的代碼,我試圖找到違反以下一致性約束的所有旅行。 每個行程的最後一站必須等於腿的旅行」錯誤111,無效使用組功能

CREATE TABLE TRIPLEG(
TNUM DECIMAL(10)  NOT NULL, 
LEGNUM DECIMAL(2) NOT NULL, 
DEPARTURE VARCHAR(30) NOT NULL,  DESTINATION VARCHAR(30) NOT NULL, 
    CONSTRAINT TRIPLEG_PKEY PRIMARY KEY (TNUM, LEGNUM), 
    CONSTRAINT TRIPLEG_UNIQUE UNIQUE(TNUM, DEPARTURE, DESTINATION), 
CONSTRAINT TRIPLEG_FKEY1 FOREIGN KEY (TNUM) REFERENCES TRIP(TNUM)); 

INSERT INTO TRIPLEG VALUES(1, 1, 'Sydney', 'Melbourne'); 
INSERT INTO TRIPLEG VALUES(1, 2, 'Melbourne', 'Hobart'); 
+0

你在where子句中使用集合函數:'MAX (T1.LEGNUM)'你不能,我會建議一個'GroupBy'和一個'Having' ... – Codexer

回答

0

嘗試以下總數;)

SELECT DISTINCT CONCAT('TOTAL NUMBER OF LEGS IN A TRIP NUMBER ', T1.TNUM, ' IS NOT EQUAL TO THE LARGEST NUMBER OF LEG IN THE TRIP') AS 'ERR' 
FROM TRIPLEG T1 
GROUP BY T1.TNUM 
HAVING COUNT(T1.TNUM) <> MAX(T1.LEGNUM) 
+1

omg它的工作原理!TT謝謝你這麼sooo –