gpt4 book ai didi

MySQL:如果在其中一个子记录中找到每个搜索条件,则选择记录

转载 作者:行者123 更新时间:2023-11-30 22:49:31 24 4
gpt4 key购买 nike

在本例中,我有 3 个表:hotels、categories、hotel_category_infos。

“酒店”表:所有酒店的列表。

-----------------------
| id | name |
-----------------------
| 1 | Hotel England |
| 2 | Hotel Scotland |
| 3 | Hotel Ireland |
| 4 | Hotel Norway |
-----------------------

“类别”表:无障碍类别列表(关于酒店对残障人士的无障碍性)。一家酒店可能被分配到的类别,甚至不止一次。

--------------------------------------------------
| id | name |
--------------------------------------------------
| 1 | Ground floor without steps |
| 2 | Washing facilities wheelchair accessible |
| 3 | Special infrastructure on location |
--------------------------------------------------

表“hotel_category_infos”:酒店类别的实际分配,以及对该酒店类别的额外精确描述。

-----------------------------------------------------------------------
| id | hotel_id | cat_id | description |
-----------------------------------------------------------------------
| 1 | 1 | 1 | No steps, except the one to the bla bla... |
| 2 | 1 | 2 | The entrance to the shower is 56cm wide... |
| 3 | 2 | 1 | The ramp at the entrance is 5% steep |
| 4 | 3 | 1 | Except on the terrace |
| 5 | 3 | 2 | Ask for rooms in the first floor |
| 6 | 3 | 3 | A indoor swimming pool is available for... |
-----------------------------------------------------------------------

我想做什么:

在搜索表单中,所有类别都列为复选框,因此在发送表单后,我有一个包含所有已选中类别 ID 的数组。我想列出分配给这些类别中的每一个类别的所有酒店(不仅是其中一个)。

我尝试过的:

例如选择所有同时提供“Ground Floor without steps”和“washing facilities”附加信息的酒店

SELECT 
hotels.id
FROM
hotels INNER JOIN hotel_category_infos ON
hotel_category_infos.hotel_id = hotels.id AND
hotel_category_infos.cat_id IN (1,2)

但是 IN() 部分建议只有一个类别必须匹配,而不是两者都匹配。我应该在 SQL 语句中更改什么?

最佳答案

请注意,这不是有效的 mysql 语法。但是,它有望为您的问题提供动态解决方案。另请注意,您需要验证传入数据以防止 sql 注入(inject)。

DECLARE p_Statement NVARCHAR(MAX)
SELECT p_Statement = 'SELECT id FROM hotels WHERE 1 = 1 '

for each p_catID in SelectedCatIds (loop) :
SELECT p_Statement = p_Statement + 'AND id IN (SELECT hotel_id FROM hotel_category_infos WHERE cat_id = p_catID '
(end loop)

PREPARE stmt FROM p_Statement
EXECUTE stmt

这会动态地将“AND id IN...”子句添加到您的查询中,从而缩小结果范围。

关于MySQL:如果在其中一个子记录中找到每个搜索条件,则选择记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28566515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com