MySQL BETWEEN与大于和小于

时间:2012-10-23 07:50:23

标签: mysql rewrite system between

我有一个有效的预订查询。此查询检查预订时可用的项目。

[PROJECT]:projectid,datefrom,dateto,...
[ITEM]:itemid,itemgroupid,...
[ITEMGROUP]:itemgroupid,itemgroupname,...
[RESERVELIST]:itemid,projectid,reservelistnr

SELECT *
FROM item i inner join itemgroup ig on i.itemgroupid = ig.itemgroupid
WHERE i.itemid NOT IN  (
                        SELECT r.itemid 
                        FROM reservelist r inner join project p on r.projectid = p.projectid
                        WHERE p.datefrom BETWEEN '$datefrom' AND '$dateto'
                        OR p.dateto BETWEEN '$datefrom' AND '$dateto'
                        OR '$datefrom' BETWEEN p.datefrom AND p.dateto
                        OR '$dateto' BETWEEN p.datefrom AND p.dateto
                        )
ORDER BY itemid 

$ datefrom和$ dateto是预订时间。
现在此查询效果很好,但如果有人在08:00 - 21:00之间进行预订,则下一次预订只能在21:01进行,而不能在21:00进行。所以我需要小于和大于。

我和<和>,但不知何故它似乎不起作用。

我最好的猜测是,这应该是一个很好的解决方案:

SELECT *
FROM item i inner join itemgroup ig on i.itemgroupid = ig.itemgroupid
WHERE i.itemid NOT IN  (
                        SELECT r.itemid 
                        FROM reservelist r inner join project p on r.projectid = p.projectid
                        WHERE p.datefrom > '$datefrom' AND p.datefrom < '$dateto'
                        OR p.dateto > '$datefrom' AND p.dateto < '$dateto'
                        OR '$datefrom' > p.datefrom AND '$datefrom' < p.dateto
                        OR '$dateto' > p.datefrom AND '$dateto' < p.dateto
                        )
ORDER BY itemid 

不幸的是,事实并非如此。

<小时/> 有人知道吗?

2 个答案:

答案 0 :(得分:1)

你必须对你的条件进行分组。而不是:

OR p.dateto > '$datefrom' AND p.dateto < '$dateto'

你想写:

OR (p.dateto > '$datefrom' AND p.dateto < '$dateto')

这样,您具有与BETWEEN相同的功能(仅具有严格的“大于”条件)。你的其他条件也一样。

最后,您的WHERE子句应如下所示:

WHERE (p.datefrom > '$datefrom' AND p.datefrom < '$dateto')
OR (p.dateto > '$datefrom' AND p.dateto < '$dateto')
OR ('$datefrom' > p.datefrom AND '$datefrom' < p.dateto)
OR ('$dateto' > p.datefrom AND '$dateto' < p.dateto)

答案 1 :(得分:0)

WHERE i.itemid NOT IN  (
                        SELECT r.itemid 
                        FROM reservelist r inner join project p on r.projectid = p.projectid
                        WHERE p.datefrom BETWEEN '$datefrom' AND '$dateto'
                        OR p.dateto BETWEEN '$datefrom' AND '$dateto'
                        OR '$datefrom' BETWEEN p.datefrom AND p.dateto
                        OR '$dateto' BETWEEN p.datefrom AND p.dateto
                        )

作品。