我有三个MySQL表,如下所示:
库存表
sn | hostname
-----------------------
1234 host123
2345 host456
4567 host789
6789 host910
预订表
orderid | serial | start_date | end_date
----------------------------------------------------------
1 1234 2015-09-10 2015-10-25
2 2345 2015-10-21 2016-02-01
2 4567 2015-10-21 2016-02-01
3 6789 2015-08-01 2015-12-31
订单明细表
order_id | assigned_to
---------------------------------
1 Mark
2 John
3 Paul
我正在尝试从这三个表中执行查询:
SELECT `serial`, `hostname`, `orderid`, `start_date`, `end_date`, `assigned_to`
FROM `reservation`, `inventory`, `orders`
WHERE `sn` IN(SELECT `serial`
FROM `reservation`
WHERE '2015-12-10' <= `end_date` AND '2015-12-10' >= `start_date`)
AND `serial` = `sn` AND `orderid` = `order_id`
在我的查询示例中,我只想显示符合我选择的日期范围的结果,但不管我选择的日期范围如何,我最终得到所有结果。示例查询结果如下:
serial | hostname | orderid | start_date | end_date | assigned_to
-----------------------------------------------------------------------------------------
1234 host123 1 2015-09-10 2015-10-25 Mark
2345 host456 2 2015-10-21 2016-02-01 John
4567 host789 2 2015-10-21 2016-02-01 John
6789 hout910 3 2015-08-01 2015-12-31 Paul
但基于上面的示例查询,我想要的结果是:
serial | hostname | orderid | start_date | end_date | assigned_to
-----------------------------------------------------------------------------------------
2345 host456 2 2015-10-21 2016-02-01 John
4567 host789 2 2015-10-21 2016-02-01 John
6789 hout910 3 2015-08-01 2015-12-31 Paul
我的查询出错了什么,我怎样才能达到预期的效果?我也尝试使用INNER JOINS
,但结果相同。
答案 0 :(得分:1)
我会删除子查询,因为它不是必需的。我正在做正确的JOIN。
SELECT
`serial`, `hostname`, `orderid`, `start_date`, `end_date`, `assigned_to`
FROM
`inventory`
JOIN
`reservation` ON `serial` = `sn`
JOIN
`orders` ON `order_id` = `orderid`
WHERE
`start_date` <= '2016-12-10' AND `start_date` >= '2015-12-10'