3

我有这样的表结构

+---+----------+------------+--------------+
| 编号| 客户 | 地址 | 地址类型 |
+---+----------+------------+--------------+
|1 | 1 | 地址 1 | 2 |
|2 | 2 | 地址 2 | 2 |
|3 | 1 | 地址 3 | 1 |
+---+----------+------------+--------------+

数据库中有两种地址类型。我必须根据以下条件选择地址

  1. 如果存在 Address_type = 1 的客户的地址,则显示该地址。
  2. 如果 Address_type = 1 不存在且 Address_type = 2 存在,则显示该客户的 Address_type = 2 地址。
  3. 如果该客户两者都存在,则仅显示 Address_type = 1 的地址

我已经通过 OR 条件尝试了这个,但它显示了数据库中第一个记录,所以 mysql 查询中有办法只用一个查询来实现这一点吗?即在数据库中同时存在 Address_types(1 和 2) 时,在 OR 条件中优先获取 Address_type = 1 记录之类的东西?

4

6 回答 6

2

您可以使用

SELECT 
  yt1.*
FROM 
  your_table yt1 
  LEFT JOIN your_table yt2 ON ( yt2.customer = yt1.customer AND yt2.address_type < yt1.address_type )
WHERE 
  yt2.id IS NULL

输出:

| ID | CUSTOMER |   ADDRESS | ADDRESS_TYPE |
-----|----------|-----------|--------------|
|  1 |        1 | Address 1 |            2 |
|  2 |        3 | Address 2 |            2 |

SQLFIDDLE

于 2013-09-10T14:28:54.243 回答
1

另一种选择:获得每个客户的最低Address_Type要求,然后加入:

SELECT
  id,
  customer,
  Address,
  Address_Type
FROM custs
INNER JOIN (
  SELECT customer, MIN(Address_Type) AS MinType
  FROM custs
  GROUP BY customer
) AddType ON custs.Address_Type = AddType.MinType
于 2013-09-10T14:23:48.813 回答
1
SELECT
  customer,
  COALESCE(
    MAX(CASE WHEN Address_type=1 THEN Address END),
    MAX(CASE WHEN Address_type=2 THEN Address END)
  )
FROM
  tableName
GROUP BY
  customer

在此处查看小提琴。

于 2013-09-10T14:29:36.413 回答
0

不需要或只要您只需要一位客户的地址:

SELECT Address FROM table WHERE customer=:customerid ORDER BY Address_type ASC LIMIT 1

这将按类型对所有地址进行排序,从 1 开始并仅返回一个地址,如果类型 1 不可用,则将返回类型 2。

于 2013-09-10T14:30:46.267 回答
0
SELECT id, customer, 
       IF(address_type=1, address, IF(address_type=2, address, null))
                  as address 
FROM customer_table
GROUP BY customer;

这样做是地址类型为 1,它使用该地址,如果为 2,则使用地址 2,否则什么也没有。

于 2013-09-10T14:12:53.113 回答
0

您可以只添加 ORDER BY Address_type ASC,这将确保 address_type 值为 1 的任何记录首先出现。我无法告诉您排序与其他方法的效率,但在我看来 ORDER BY 是最简单的解决方案。

于 2013-09-10T14:20:41.080 回答