如何选择一个字段位于多个字段中的行

时间:2016-08-25 13:23:25

标签: mysql sql

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

             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.这不仅仅是问题本身,而是唯一的问题。我发现这样做的方法非常笨重,并且不会为将来的打样留下很多选择。

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),但这会导致错误。

3 个答案:

答案 0 :(得分:2)

你可以尝试连接这样的表:

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%'

答案 1 :(得分:1)

您可以使用JOIN

SELECT DISTINCT b.* 
FROM   buildings b 
       JOIN postal_codes pc 
         ON b.building_code IN ( pc.primary, pc.secondary ) 
WHERE  postal_code LIKE '%A1A%' 

注意:使用Distinct以避免来自Building表的重复记录,因为您的原始内容不会重复结果。如果您的postal_codes表格在pc.primarypc.secondary列中没有重复条目,则可以删除Distinct

或者您可以使用EXISTS

SELECT * 
FROM   buildings B 
WHERE  EXISTS (SELECT 1 
               FROM   postal_codes PC 
               WHERE  B.building_code IN ( pc.primary, pc.secondary ) 
                      AND PC.postal_code LIKE '%A1A%') 

答案 2 :(得分:0)

SELECT b.*
FROM
(
SELECT primary as b_id FROM postal_codes WHERE postal_code LIKE '%A1A%'
UNION DISTINCT
SELECT pecondary as b_id FROM postal_codes WHERE postal_code LIKE '%A1A%'
) x
inner join buildings as b on x.b_id = b.building_code