2011-08-04 81 views
0

我查詢如何使用JOIN和WHERE語句篩選記錄?

SELECT table1.name, table2.wage, table2.bonus table3.shift, table4.vacation 
    FROM table1 
INNER JOIN table2 ON table1.userid = table2.userid 
INNER JOIN table3 ON table2.userid = table3.userid 
INNER JOIN table4 ON table4.userid = table4.userid 
LEFT JOIN table5 ON table1.name = table5.position 
**LEFT JOIN vacation on vacation.userid = table1.userid 
WHERE vacation.userid IS NULL**; 

這將選擇所有其中userid是不是裏面的假期表。

現在我需要檢查用戶ID是否在休假表內,並且如果vacation.status = 1對於此userid仍應顯示在查詢中。

回答

1

如果這是一個單獨的查詢/要求的話,下面的查詢將工作:

SELECT table1.name, table2.wage, table2.bonus table3.shift, table4.vacation 
    FROM table1 
INNER JOIN table2 ON table1.userid = table2.userid 
INNER JOIN table3 ON table2.userid = table3.userid 
INNER JOIN table4 ON table4.userid = table4.userid 
INNER JOIN vacation on vacation.userid = table1.userid 
LEFT JOIN table5 ON table1.name = table5.position 
WHERE vacation.status = 1; 

如果您需要兩方面的要求(用戶ID爲NULL或狀態= 1),試試這個:

SELECT table1.name, table2.wage, table2.bonus table3.shift, table4.vacation 
    FROM table1 
INNER JOIN table2 ON table1.userid = table2.userid 
INNER JOIN table3 ON table2.userid = table3.userid 
INNER JOIN table4 ON table4.userid = table4.userid 
LEFT JOIN table5 ON table1.name = table5.position 
LEFT JOIN vacation on vacation.userid = table1.userid 
WHERE vacation.user_id IS NULL or vacation.status = 1; 
+0

它需要是相同的查詢,我試過,但它並沒有爲我工作,現在它正在與你的例子,謝謝兄弟。 – BUddhaxx