我有以下关于mysql的问题
我先给我的数据库看看,然后看看我想要什么,然后看看我做了什么,没有做什么
我有下表
DB:客户服装

+-------------------+-------------------+-------------------+---------------+---------------+
|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>从customeradress中选择不同的customeradress\u id

MYSQL>按customeradress从customeradress组中选择customeradress\u id
我得到以下结果
+-----------------------+
|customeradress_id  |
+-----------------------+
+-----------------------+
|01      |
+-----------------------+
|02      |
+-----------------------+
|03      |
+-----------------------+
|04      |
+-----------------------+

有人能帮我吗?

最佳答案

基本原理是这样的
内部select get的所有客户名称都是唯一的。如果客户有一个zip,那么最小(或最大)将检索一个zipcode。
再次将内部select与原始表连接将删除客户具有空zipcode的行(如果有其他zipcode可用)
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, '')

10-07 17:58