如何使用JOIN和WHERE语句过滤记录?

时间:2011-08-04 12:04:44

标签: mysql join filter

我的查询

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的{​​{1}}是否仍应在查询中显示。

1 个答案:

答案 0 :(得分: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;

如果您需要两个要求(userid为NULL或status = 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;