gpt4 book ai didi

mysql - 如何在 MySQL JOIN 的同一列中搜索多个值?

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

我已尽力解释我的问题。请仔细阅读我的问题以了解我想要实现的目标。

我试图在 MySQL 的同一列中搜索多个值。我在此操作中使用了以下 4 个表,它们是:

联系人:

enter image description here

数据值:

enter image description here

数据字段:

enter image description here

data_cats_options:

enter image description here

在我的网站前端,过滤器(用于搜索所需数据的表单元素)如下所示:

enter image description here

enter image description here

单下拉(国家)搜索:

要获取名称为“Sachin”且“国家/地区”为“印度”的所有联系人,我使用以下查询:

SELECT `c`.* 
FROM `contacts` AS `c` JOIN `data_values` AS `dv`
ON `c`.`contact_id` = `dv`.`contact_id`
JOIN `data_fields` AS `df` ON
`dv`.`field_id` = `df`.`field_id`
JOIN `data_cats_options` AS `dco` ON
`dv`.`field_val` = `dco`.`val_id`
WHERE `c`.`contact_name` = "Sachin" AND `dv`.`field_id` = 153 AND `dco`.`val_id` = 224

同样,我们可以为所有负责“工作”下拉列表的“Sachin”做。

问题

我真的不知道如何搜索多个数据,例如如何获取“Sachin”的所有联系人,其“Country”是“India”且“Job”是“Accountant”。尽管数据存在于数据库中,但以下 SQL 没有给我任何结果:

SELECT `c`.* 
FROM `contacts` AS `c` JOIN `data_values` AS `dv`
ON `c`.`contact_id` = `dv`.`contact_id`
JOIN `data_fields` AS `df` ON
`dv`.`field_id` = `df`.`field_id`
JOIN `data_cats_options` AS `dco` ON
`dv`.`field_val` = `dco`.`val_id`
WHERE `c`.`contact_name` = "Sachin" AND `dv`.`field_id` = 153 AND `dco`.`val_id` = 224
AND `dv`.`field_id` = 154 AND `dco`.`val_id` = 227

我主要关心的是上述查询的这个特定部分:

AND `dv`.`field_id` = 153 AND `dco`.`val_id` = 224 
AND `dv`.`field_id` = 154 AND `dco`.`val_id` = 227

那么我们如何在这个 JOIN 中搜索同一列中的多个数据呢?

我真的很想获取所有满足两个下拉选项的记录。

请帮我解决这个问题。提前致谢。

最佳答案

这似乎是一个糟糕的设计,因为我们必须添加额外的连接。

SELECT c.* 
FROM contacts AS c
JOIN data_values AS dv
ON c.contact_id = dv.contact_id
JOIN data_fields AS df
ON dv.field_id = df.field_id
JOIN data_cats_options AS dco
ON dv.field_val = dco.val_id
JOIN data_values AS dv2
ON c.contact_id = dv2.contact_id
JOIN data_fields AS df2
ON dv2.field_id = df2.field_id
JOIN data_cats_options AS dco2
ON dv2.field_val = dco2.val_id
WHERE c.contact_name = "Sachin"
AND dv.field_id = 153 AND dco.val_id = 224
AND dv2.field_id = 154 AND dco2.val_id = 227

我仍在考虑其他选择,但需要做一些其他事情。

也许... 2 会根据正在搜索的 field_ID 的数量动态设置;你知道,因为你有 field_IDs...

SELECT c.contact_ID, C.Contact_name
FROM contacts AS c
JOIN data_values AS dv
ON c.contact_id = dv.contact_id
JOIN data_fields AS df
ON dv.field_id = df.field_id
JOIN data_cats_options AS dco
ON dv.field_val = dco.val_id
WHERE c.contact_name = "Sachin"
AND (dv.field_id = 153 AND dco.val_id = 224
OR dv.field_id = 154 AND dco.val_id = 227)
GROUP BY c.contact_ID, C.Contact_name
HAVING count(*) = 2

为什么这有效?因为我们知道,如果两者都匹配,我们将为每个 contact_ID 获得 2 条记录,如果两者都不存在,我们只会获得 1 条记录。因此,拥有让我们限制了所需的方式。

或者我们可以使用HAVING COUNT() = (Select count() from data_Fields where field_ID in ('153','154'))

关于mysql - 如何在 MySQL JOIN 的同一列中搜索多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53654219/

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