2016-02-08 57 views
0

這裏是複雜的查詢,我寫的,但不能弄清楚什麼問題:MySQL的語法錯誤對於複雜查詢

SELECT student.progid, 
    student.batch 
FROM (student 
    JOIN registers 
     ON student.studentid = registers.studentid) 
    JOIN (SELECT offers.courseno 
     FROM (offers 
       JOIN instructor 
        ON offers.instructorid = instructor.instructorid)) 
    ON offers.courseno = registers.courseno 
WHERE instructor.instructorname = 'P M Jaat' 
    AND (offers.acadyear LIKE '2007%' 
      OR offers.acadyear LIKE '2008%' 
      OR offers.acadyear LIKE '2009%' 
      OR offers.acadyear LIKE '2010%' 
      OR offers.acadyear LIKE '2011%'); 

這將導致一個錯誤,但我會離開它別人告訴你這是什麼:

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 near 'R1 
    JOIN (SELECT 
+1

你能告訴我們您所看到的語法錯誤? –

+0

'FROM(student ...'是否正確? – Kisaragi

+0

學生是表名,是正確的。 –

回答

3

仔細檢查你的括號。您的FROM條款是

(student JOIN registers ON student.StudentID=registers.StudentID) 

這是沒有意義的。

你想要的是:

FROM (student) 
JOIN registers AS r1 
    ON (student.StudentID=registers.StudentID) 

或者,你可以失去多餘的括號:

FROM student 
JOIN registers AS r1 
    ON student.StudentID=registers.StudentID 

附:你也有你的AS r1在錯誤的地方。

更新:當您使用子查詢時需要括號。

FROM student 
JOIN registers 
    ON student.studentid = registers.studentid 
JOIN(
    SELECT courseno 
    FROM offers 
    JOIN instructor 
    ON offers.instructorid = instructor.instructorid 
) AS r2 ON offers.courseno = registers.courseno 
+0

aaaah,爲什麼MySQL語法不像C或Java那麼簡單! –

+0

雖然我不希望寄存器爲r1。它顯示派生表必須有它自己的別名錯誤沒有它。 –

+0

你想要什麼'r1'? –

2

也許你是這樣的事情後...

SELECT r.progid 
     , r.batch 
     FROM student s 
     JOIN registers r 
     ON r.studentid = s.studentid 
     JOIN offers o 
     ON o.courseno = r.courseno 
     JOIN instructor i 
     ON i.instructorid = o.instructorid 
    WHERE i.instructorname = 'P M Jaat' 
     AND o.acadyear BETWEEN '2007-01-01' AND '2011-12-31'; 
+0

這似乎比我的答案好多了。沒有理由在這裏使用子查詢,只是加入你需要的一切。 –

+0

它工作!只是如此你知道,它沒有奏效,因爲我的年份不是你的格式。我編輯成我的格式。這個很簡單。這讓我想知道爲什麼我覺得這麼複雜。 –

+0

@ Mr.Robot一個更好的主意可能是將你的年份調整爲*我*格式!它會更快(雖然你的數據集可能很小) – Strawberry