gpt4 book ai didi

mysql - 如何选择一个字段在多个字段中的行

转载 作者:行者123 更新时间:2023-11-29 05:11:08 24 4
gpt4 key购买 nike

我正在尝试查询我的数据库以返回与输入的邮政编码匹配的所有建筑物。我的客户向我提供了与该主题相关的两个表格:

             buildings
+----+------------+---------------+
| id | name | building_code |
+----+------------+---------------+
| 1 | Building A | 001 |
| 2 | Building B | 002 |
| 3 | Building C | 003 |
+----+------------+---------------+

postal_codes
+----+-------------+---------+-----------+
| id | postal_code | primary | pecondary |
+----+-------------+---------+-----------+
| 1 | A1A 1A1 | 001 | 002 |
| 2 | B2B 2B2 | 002 | 003 |
| 3 | C3C 3C3 | 003 | 001 |
+----+-------------+---------+-----------+

对我来说不幸的是,包含邮政编码的表格包含重复的建筑代码(邮政编码有一个主要建筑物和一个次要建筑物)

因此,在搜索邮政编码为 A1A 的建筑物时,我需要接收建筑物 A 和建筑物 B。这本身并不是什么大问题,但是我发现这样做的唯一方法非常庞大,并且没有为 future 的验证留下很多选择。

SELECT * FROM buildings
WHERE (building_code IN (SELECT primary FROM postal_codes
WHERE postal_code LIKE '%A1A%')
OR
building_code IN (SELECT secondary FROM postal_codes
WHERE postal_code LIKE '%A1A%'))

我试过只做 building IN (SELECT primary, secondary FROM postal_codes) 但这一直导致错误。

最佳答案

您可以尝试像这样连接表:

select b.* 
from postal_codes p
join buildings b
on b.building_code = p.primary OR b.building_code = p.secondary
where p.postal_code LIKE '%A1A%'

关于mysql - 如何选择一个字段在多个字段中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39146567/

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