难以在SQL查询中放置2个WHERE

时间:2013-02-16 01:36:06

标签: mysql

我的SQL查询出了什么问题?

它在WHERE building_id=:building_id

处不断返回以下错误
  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   '附近':building_id和WHERE NOT EXISTS(从ts_roompref中选择1)   在第5行:SELECT COUNT(*)totalCount FROM ts_room WHERE   building_id =:building_id AND WHERE NOT EXISTS(SELECT 1 FROM   ts_roompref JOIN ts_request ON ts_roompref.request_id =   ts_request.roompref_id AND day_id = 1 AND period_id = 1 WHERE   ts_room.id = ts_roompref.room_id)

这是我的代码:

SELECT 
  COUNT(*) totalCount 
FROM 
  ts_room 
WHERE building_id=:building_id AND
WHERE 
  NOT EXISTS (
    SELECT 1
    FROM ts_roompref 
      JOIN ts_request 
      ON ts_roompref.request_id = ts_request.roompref_id
      AND day_id = 1 
      AND period_id = 1
    WHERE 
      ts_room.id = ts_roompref.room_id)

我在这里有一个SQL表 - http://sqlfiddle.com/#!2/30297/8

4 个答案:

答案 0 :(得分:3)

只需删除第二个WHERE关键字。

由于:buildingid而无法在SQL Fiddle中编译。

Here's a working example

答案 1 :(得分:2)

在AND

之后不需要第二个WHERE
... WHERE building_id=:building_id AND NOT EXISTS ...

答案 2 :(得分:2)

您只需要一个WHERE

SELECT 
  COUNT(*) totalCount 
FROM 
  ts_room 
WHERE building_id=:building_id AND

  NOT EXISTS (
    SELECT 1
    FROM ts_roompref 
      JOIN ts_request 
      ON ts_roompref.request_id = ts_request.roompref_id
      AND day_id = 1 
      AND period_id = 1
    WHERE 
      ts_room.id = ts_roompref.room_id)

答案 3 :(得分:2)

AND之后,你不应该第二次写WHERE