为什么这个WHERE子句不能用于Join?

时间:2012-10-13 04:52:12

标签: mysql sql

我对SQL很陌生,这是一个复杂的命令:

SELECT users.name, 
       from_unixtime(activity.time_stamp, "%D %b %Y  %l:%i:%S"), 
      activity.activity, 
      activity.rfid_tag, 
      chemicals.description 
FROM activity 
JOIN chemicals ON chemicals.bar_code = activity.bar_code 
JOIN users ON users.badge_number=activity.badge_number 
WHERE  (activity="login") 
    OR (activity="logout") 
   OR (activity LIKE "Admin:%") 
   OR (activity="tag") 
   OR (activity="untag") 
   OR (activity LIKE "check out%") 
   OR (activity LIKE "pour%") 
   OR (activity="check out (unscheduled)") 
   OR (activity="not poured after checking out") 
   OR (activity LIKE "invalid:%") 
ORDER BY time_stamp DESC

当我运行它时,它只返回 与WHERE的最后一个OR匹配的行(来自867的723)。例如,我没有看到activity =“login”的任何行,但SELECT * FROM activity WHERE activity="login"确实返回了一些行。

谁能告诉我我做错了什么? (如果那应该是“INNER JOIN”)?


[更新]在添加Join之前我应该​​说这是有效的(复杂的WHERE)(我是一个完整的SQL n00b)

1 个答案:

答案 0 :(得分:4)

请研究INNER JOIN and LEFT JOIN之间的区别。

从查看您的查询和基于名称并与现实世界实体相关的水晶球注视,这是我能看到的:

当您的活动“倒”时,它可能涉及一些化学品,它将成功加入条形码。当它是“登录”时,我怀疑你会得到一个成功的(内部)加入化学表。正如有人提到的那样,你真的想把它们变成LEFT JOIN,例如

SELECT users.name, 
       from_unixtime(activity.time_stamp, "%D %b %Y  %l:%i:%S"), 
      activity.activity, 
      activity.rfid_tag, 
      chemicals.description 
FROM activity 
LEFT JOIN chemicals ON chemicals.bar_code = activity.bar_code 
LEFT JOIN users ON users.badge_number=activity.badge_number 
WHERE  (activity="login") 
   OR (activity="logout") 
   OR (activity LIKE "Admin:%") 
   OR (activity="tag") 
   OR (activity="untag") 
   OR (activity LIKE "check out%") 
   OR (activity LIKE "pour%") 
   OR (activity="check out (unscheduled)") 
   OR (activity="not poured after checking out") 
   OR (activity LIKE "invalid:%") 
ORDER BY time_stamp DESC