Mysql子查询 - 需要在两个类似的查询之间建立连接,以便计算邮政编码和邮政编码的出现次数

时间:2011-07-08 17:44:34

标签: mysql subquery zipcode postal-code

我有一个问题要解决这个问题。我需要将两个查询放在一起,无论我尝试过什么,我总是在mysql语法中出错。这两个查询如下。

查询1 - 这是针对加拿大邮政编码

SELECT ta.city, ta.email_address, ta.country_code, COUNT(*)
FROM jos_form_submitteddata_form1 tb
JOIN jos_postalzip_redirect ta ON UPPER(LEFT(tb.FIELD_24, 3)) = LEFT(ta.postal_zip, 3)
WHERE LENGTH(tb.FIELD_24) > 5
GROUP BY ta.city;  

查询2 - 如果是美国邮政编码

SELECT ta.city, ta.email_address, ta.country_code, COUNT(*)
FROM jos_form_submitteddata_form1 tb
JOIN jos_postalzip_redirect ta ON UPPER(tb.FIELD_24) = LEFT(ta.postal_zip, 5)
WHERE LENGTH(tb.FIELD_24) <= 5
GROUP BY ta.city
HAVING ta.country_code = 'US';

目标是让这两个查询在同一个表中显示正确的计数

2 个答案:

答案 0 :(得分:0)

UNION不能满足您的需求吗?

SELECT ta.city, ta.email_address, ta.country_code, COUNT(*) 
FROM jos_form_submitteddata_form1 tb 
JOIN jos_postalzip_redirect ta ON UPPER(LEFT(tb.FIELD_24, 3)) = LEFT(ta.postal_zip, 3)
WHERE LENGTH(tb.FIELD_24) > 5 GROUP BY ta.city
UNION
SELECT ta.city, ta.email_address, ta.country_code, COUNT(*) 
FROM jos_form_submitteddata_form1 tb 
JOIN jos_postalzip_redirect ta ON UPPER(tb.FIELD_24) = LEFT(ta.postal_zip, 5) 
WHERE LENGTH(tb.FIELD_24) <= 5 AND ta.country_code = 'US' GROUP BY ta.city

答案 1 :(得分:0)