我有关于mysql的以下问题
首先,我会展示我的数据库,然后是我想要的,然后我做了什么,什么都不行
我得到了下表
DB: customeradress
+-------------------+-------------------+-------------------+---------------+---------------+
|customeradress_id | customername_id | customeradres | customerZip | customerplace |
+-------------------+-------------------+-------------------+---------------+---------------+
+-------------------+-------------------+-------------------+---------------+---------------+
|01 | 01 | streetA 1 | 1234AB | PlaceA |
+-------------------+-------------------+-------------------+---------------+---------------+
|02 | 04 | streetZ 99 | 9901ZZ | PlaceZ |
+-------------------+-------------------+-------------------+---------------+---------------+
|03 | 99 | streetXY 11 | | PlaceB |
+-------------------+-------------------+-------------------+---------------+---------------+
|04 | 01 | streetA 1 | | PlaceA |
+-------------------+-------------------+-------------------+---------------+---------------+
|05 | 01 | streetA 1 | 1234AB | PlaceA |
+-------------------+-------------------+-------------------+---------------+---------------+
我想要的是什么:
我想对数据库进行查询,它给了我唯一的记录,当有多个记录,其中1表示有一个customerZip而不是, 然后返回填写了customerZip的那个。结果应如下所示:
+-----------------------+
|customeradress_id |
+-----------------------+
+-----------------------+
|01 |
+-----------------------+
|02 |
+-----------------------+
|03 |
+-----------------------+
我做了什么:
当我使用此查询时:
MYSQL> SELECT DISTINCT customeradress_id FROM customeradress
和
MYSQL> SELECT customeradress_id FROM customeradress GROUP BY customeradress_id
我得到以下结果
+-----------------------+
|customeradress_id |
+-----------------------+
+-----------------------+
|01 |
+-----------------------+
|02 |
+-----------------------+
|03 |
+-----------------------+
|04 |
+-----------------------+
有人能帮助我吗?
答案 0 :(得分:1)
理由就像这样
SQL声明
SELECT DISTINCT customeradress_id
FROM customeradress ca
INNER JOIN (
SELECT customername_id
, customerZip = MIN(customerZip)
FROM customeradress
GROUP BY
customer_name_id
) cag ON cag.customername_id = ca.customername_id
AND ISNULL(cag.customerZip, '') = ISNULL(ca.customerZip, '')
答案 1 :(得分:0)
首先,您需要重复的客户地址,即customer_id和amp;的集合。 customeradress成对超过一行。然后,您希望找到与customer_id和customeradres对匹配的所有行,并过滤掉空值。
试试这个:
select ca.customeradress_id
from
customeradress ca inner join
(select customer_id, customeradres
from customeradress
group by customer_id, customeradres
having count(*) > 1) t1 on t1.customer_id = ca.customer_id and t1.customeradres = ca.customeradres
where
ca.customerZip is not null
子选择对customer_id和customeradres上的行进行分组,而having子句仅对具有多个出现次数的行进行过滤,即重复。这组customer_id和customeradres内部连接到同一个表,以便只返回匹配的行。然后where子句只过滤到带有ZIP的那些。