2011-04-28 83 views
3
SELECT E.id_employee,E.name,E.age,E.wage,D.name, 
    CASE (SELECT COUNT(*) FROM manages M 
     WHERE M.id_employee=E.id_employee) 
     WHEN 1 THEN 'Chief' 
     WHEN 0 THEN '-' 
    END CASE 
FROM Employee E 
INNER JOIN work_in 
INNER JOIN Department D 

它給人的錯誤:我的MySQL查詢出了什麼問題?

無法連接:您的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在附近使用正確的語法'CASE FROM Employee E INNER JOIN work_in INNER JOIN部門D'第5行

我在這裏丟失了什麼?請立即幫忙。

回答

3

有 'END' 後沒有 '案例'

SELECT E.id_employee,E.name,E.age,E.wage,D.name, 
       CASE (SELECT COUNT(*) FROM manages M WHERE M.id_employee=E.id_employee) 
        WHEN 1 THEN 'Chief' 
        WHEN 0 THEN '-' 
       END 
FROM Employee E INNER JOIN work_in INNER JOIN Department D 
+1

http://dev.mysql.com/doc/refman/5.0/en/case-statement.html不同意。 – Nik 2011-04-28 15:49:44

+0

它是'END CASE' – 2011-04-28 15:52:23

+2

好吧,不在查詢中... http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html。這是兩種不同的CASE聲明,OP需要沒有END CASE的聲明。 – 2011-04-28 15:52:40

3

從END之後刪除單詞爲例。

1

您缺少ON條件爲inner joinUSING()條款。

SELECT E.id_employee,E.name,E.age,E.wage,D.name, 
       CASE (SELECT COUNT(*) FROM manages M WHERE M.id_employee=E.id_employee) 
        WHEN 1 THEN 'Chief' 
        WHEN 0 THEN '-' 
       END 
      FROM Employee E 
       INNER JOIN work_in w 
        ON e.id_employee=w.id.employee 
       INNER JOIN Department D 
        ON w.id_department=D.id_department 
+0

你會注意到'INNER JOIN'上的* join條件是可選的:'join_table:table_reference [INNER | CROSS] JOIN table_factor [join_condition] | ...' – Orbling 2011-04-28 15:56:02

+0

@ Orbling - 當然,這是可選的,但是您認爲查詢會通過沒有它的語法檢查?它只是可選的,有兩個原因:由於CROSS JOIN,並且因爲可以對連接條件使用USING()或WHERE子句。他有一個內部連接,沒有指定。 – dawebber 2011-04-28 16:01:17

+0

@dawebber,測試它,下面的查詢確實工作:'select * from table1 inner join table2;'奇怪的是,它做了一個完整的外連接:-) – Johan 2011-04-28 19:56:26

4

刪除最後一個CASE關鍵字,則END

1

其更改後:

"SELECT E.id_employee,E.name,E.age,E.wage,D.name, 
    CASE (SELECT COUNT(*) FROM manages M WHERE M.id_employee=E.id_employee) 
    WHEN 1 THEN 'Chief'      
    WHEN 0 THEN '-'     
    END    
FROM Employee E 
INNER JOIN work_in w ON (w.id = e.work_id) 
INNER JOIN Department D ON (D.id = e.department_id)" 

警告
如果你沒有條件(S),它會做一個inner join實際上變成了full outer join
這意味着如果你運行下面的查詢:

SELECT * FROM a 
INNER JOIN b 
INNER JOIN c 

,其中表a,b和c分別有100行,您將得到總計爲1,000,000行,在你的結果集,列出的每一個可能的組合, b和c。
在99,999%的情況下,這絕對不是你想要的。

2

您在混合使用CASE StatementCASE expression的語法。雖然第一個用於存儲過程,但第二個用於SQL語句中。

CASE表達

SELECT CASE 1 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'more' END; 

CASE聲明

CASE case_value 
    WHEN when_value THEN statement_list 
    [WHEN when_value THEN statement_list] ... 
    [ELSE statement_list] 
END CASE 

或以手動把它

Note

The syntax of the CASE statement used inside stored programs differs slightly from that of the SQL CASE expression described in Section 11.4, 「Control Flow Functions」. The CASE statement cannot have an ELSE NULL clause, and it is terminated with END CASE instead of END.

所以你的情況在END之後沒有CASE