我有 2 个表,比如邮政编码的主表,以及一个包含当前地址和永久地址的事务表。两个地址列都会有邮政编码。我需要根据主邮政编码表验证这 2 个邮政编码。
Master Table:
+--------+--------------+-----+
|zip_code|territory_name|state|
+--------+--------------+-----+
| 81A02| TERR NAME 02| NY|
| 81A04| TERR NAME 04| FL|
| 81A05| TERR NAME 05| NJ|
| 81A06| TERR NAME 06| CA|
| 81A07| TERR NAME 06| CA|
+--------+--------------+-----+
Transaction table:
+--------+--------------+-----+
|Address1_zc|Address2_zc|state|
+--------+--------------+-----+
| 81A02| 81A05| NY|
| 81A04| 81A06| FL|
| 81A05| 90005| NJ|
| 81A06| 90006| CA|
| 41A06| 81A06| CA|
+--------+--------------+-----+
结果集应仅包含 ADDRESS1_ZC 和 ADDRESS2_ZC 中的有效邮政编码。
+-----------+-----------+-----+
|Address1_zc|Address2_zc|state|
+-----------+-----------+-----+
| 81A02 | 81A05 | NY |
| 81A04 | 81A06 | FL |
+-----------+-----------+-----+
我尝试了以下 SQL,但无法获得所需的结果。
select a.Address1_zc, a.Address2_zc from tran_table a
join master_table b
on a.Address1_zc = b.zipcode
or a.Address2_zc = b.zipcode
select a.Address1_zc, a.Address2_zc from tran_table a
where a.Address1_zc in (select zipcode from master_table b)
union
select a.Address1_zc, a.Address2_zc from tran_table a
where a.Address2_zc in (select zipcode from master_table b)
上述查询获取有效/无效的邮政编码。请帮助我。
谢谢
最佳答案
您可以使用简单的INNER JOIN
。以下将返回主表中存在两个邮政编码的行。它假设主表不包含重复的邮政编码。
SELECT tran_table.*
FROM tran_table
INNER JOIN master_table AS m1 ON tran_table.address1_zc = m1.zip_code
INNER JOIN master_table AS m2 ON tran_table.address2_zc = m2.zip_code
关于MySql 查询 - 根据主表验证表中两列中的邮政编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57624147/