[英]SQL Left Join - Multiple Rows in Right Table
I am trying to make PHP / MySQL Search Form. 我正在尝试制作PHP / MySQL搜索表单。 When a user wants to search he need to fill 3 input fields: FromDate , ToDate and SucategoryID .
用户想要搜索时,需要填写3个输入字段: FromDate , ToDate和SucategoryID 。
There are 2 tables: Items and ItemsBlockDates In Table Items, there is info about the item and it is identified by ID. 有2个表: Items和ItemsBlockDates在Table Items中,有关于该项目的信息,并由ID标识。 In Table ItemBlockDates, there is info about a period when Item will not be displayed in search results.
在表ItemBlockDates中,有关于一段时间的信息,该期间不会在搜索结果中显示Item。 It contains: ItemID, FromDate , and Date fields.
它包含: ItemID,FromDate和Date字段。 Also, there is a possibility to define more than one Block Date for one item.
同样,有可能为一项定义多个“冻结日期”。
Now, I want to select all Items where FromDate and To Date inputs does not match with any of rows in ItemsBlockDates with same ItemID. 现在,我要选择FromDate和To Date输入与具有相同ItemID的ItemsBlockDates中的任何行都不匹配的所有项。
I wrote a query, but there is a problem: 我写了一个查询,但是有一个问题:
SELECT *
FROM Items
LEFT JOIN ItemBlockDates ON Items.ID = ItemBlockDates.ItemID
WHERE Items.SubcategoryID = :SubcategoryID
AND ItemBlockDates.FromDate NOT BETWEEN CAST(:FromDate AS DATETIME) AND CAST(:ToDate AS DATETIME)
When I run this query it does not display Items where Block Dates are not set, also it displays items where more than one Block Date is set. 当我运行此查询时,它不会显示未设置“阻止日期”的项目,也不会显示设置了多个“阻止日期”的项目。
I want to select all Items where FromDate and To Date inputs does not match with any of rows in
ItemsBlockDates
with same ItemID.我要选择FromDate和To Date输入与具有相同ItemID的
ItemsBlockDates
任何行都不匹配的所有项。
To me, this suggests NOT EXISTS
: 对我来说,这表明
NOT EXISTS
:
SELECT i.*
FROM Items i
WHERE i.SubcategoryID = :SubcategoryID AND
NOT EXISTS (SELECT 1
FROM ItemBlockDates ibd
WHERE i.ID = ibd.ItemID AND
ibd.FromDate BETWEEN CAST(:FromDate AS DATETIME) AND CAST(:ToDate AS DATETIME)
);
If you are passing in a parameter, I'm not sure why you need to convert to a DATETIME
. 如果您要传递参数,则不确定为什么要转换为
DATETIME
。 You should be able to pass it in with the correct type. 您应该能够以正确的类型传递它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.