使用MySQL WHERE子句中的子查询

时间:2012-07-18 11:40:16

标签: mysql where-clause

我根本不是sql guru,但为什么这个查询会返回错误?

SELECT username FROM history as h 
    WHERE username IS NOT NULL AND updated>1342555201 AND updated<1342641599
    AND WHERE (SELECT status FROM managers WHERE username=h.username) > 0

如何使用包含状态的第二个表上的子查询在一个查询中对状态为> 0的用户名进行分组?

3 个答案:

答案 0 :(得分:2)

你不应该有2个WHERE语句

编辑:

也 - 你应该加入经理表

答案 1 :(得分:2)

SELECT h.username FROM history  h 
INNER JOIN status s USING(username)
WHERE h.updated BETWEEN 1342555201 AND 1342641599
GROUP BY h.username
HAVING  s.status > 0

注意:

  • INNER JOIN将始终检索NOT NULL和用户名
  • 的常用值
  • 我假设两个表都有相同的列名。如果两个表都有不同的列名,那么更改

    USING(username)ON h.column_name = s.column_name

答案 2 :(得分:1)

你有一个where太多了。

SELECT username FROM history as h 
WHERE username IS NOT NULL AND updated>1342555201 AND updated<1342641599
AND WHERE (SELECT status FROM managers WHERE username=h.username) > 0
    ^^^^^