SQL WHERE查询,编辑现有查询

时间:2015-02-15 14:03:43

标签: mysql sql sql-server join where

我正在完成一项工作,其中一位负责SQL的团队成员已经去度假了。 我有以下查询:

SELECT
    Car.*, 
    Building.*, 
    CarType.* 
FROM 
    Car 
    INNER JOIN Building ON 
        Car.BuildingID=Building.BuildingID 
    INNER JOIN CarType ON 
        Car.CarType=CarType.TypeID

这将返回我们需要的所有关于汽车和建筑物的信息,但是,我们需要编辑查询,以便根据Request表中的字段值,称为status,如果此字段不是= '接受',然后不显示有关建筑物或汽车的信息?

我尝试了以下内容:

SELECT 
    Car.*, 
    Building.*, 
    CarType.*, 
    Requests.* 
FROM
    Car 
    INNER JOIN Building ON 
        Car.BuildingID=Building.BuildingID 
    INNER JOIN CarType ON 
        Car.CarType=CarType.TypeID 
WHERE 
    Requests.Status <> 'Accepted'

然而,这不起作用 任何帮助,将不胜感激 谢谢

2 个答案:

答案 0 :(得分:0)

以下查询将仅返回Car,Building和cartype信息其中状态仅为&#39;已接受&#39;不是其他的

SELECT Car.*, Building.*, CarType.*
FROM Car INNER JOIN Building 
ON Car.BuildingID=Building.BuildingID INNER JOIN CarType ON     
Car.CarType=CarType.TypeID 
/* add here joining of Requests Table */
WHERE Requests.Status = 'Accepted'

<强>更新

/* add one line from below lines into the just below where Clause 
 as per your Table hierarchy */
INNER JOIN Requests.ReqID= Car.ReqID 
INNER JOIN Requests.ReqID= Building.ReqID
INNER JOIN Requests.ReqID= CarType.ReqID

答案 1 :(得分:0)

您缺少查询中的请求表。假设Car Table中有一个字段RequestID,您的查询应该看起来像

SELECT Car.*, Building.*, CarType.*
FROM Car 
INNER JOIN Building ON Car.BuildingID=Building.BuildingID
INNER JOIN CarType ON Car.CarType=CarType.TypeID
INNER JOIN Requests ON Car.RequestID = Requests.RequestID
WHERE Requests.Status = 'Accepted'

注意我已将Requests表加入Car表假设两者都包含一个名为RequestID的字段