在 MySQL 中创建一个带有自定义字符串的别名列

Make an alias column with custom string in MySQL

我有一个 MySQL table 是这样的:

##customer##
+-----------+----+---------+
|customer_id|name|telephone|
+-----------+----+---------+
|     1     |Andi|+62932011|
|     2     |Boby|+62928291|
|     3     |Jane|+62932212|
|     4     |John|+62999021|
|     5     |Beth|+62999021|
|     6     |Noel|+62999021|
+-----------+----+---------+

##plus_membership##
+-----------------+-----------+-------+------------+
|plus_membership_id|customer_id|status |requested_at|
+------------------+-----------+-------+------------+
|        1         |     1     |   1   | 2018-11-01 |
|        2         |     2     |   0   | 2018-11-03 |
|        3         |     4     |   2   | 2018-11-04 |
|        4         |     6     |   1   | 2018-11-05 |
+------------------+-----------+-------+------------+

上面的结构中有两个table,第一个是customer,主键是customer_id,第二个是plus_membership,主键是plus_membership外键customer_idplus_membership table 是一个table 表示如果客户要求成为plus 会员,状态1 表示客户已获批准成为加号会员。我需要 select 客户 table 并添加别名列假设别名列名称是 membership ,仅显示 regularplusplus 表示plus_membership 状态的客户是 1,如果 plus_membership table 中不存在客户或 table 中的状态不是 1,则为常规客户。例如:

SELECT *, .... AS membership FROM customer;

+-----------+----+---------+----------+
|customer_id|name|telephone|membership|
+-----------+----+---------+----------+
|     1     |Andi|+62932011|   Plus   |
|     2     |Boby|+62928291|  Regular |
|     3     |Jane|+62932212|  Regular | 
|     4     |John|+62999021|  Regular |
|     5     |Beth|+62999021|  Regular |
|     6     |Noel|+62999021|   Plus   |
+-----------+----+---------+----------+

可以在两个table之间使用Left Join,并使用Case .. When条件表达式相应地计算membership

Left Join 将确保考虑来自 customer table 的所有客户,无论他们是否在 plus_membership table与否。

SELECT
 c.customer_id, 
 c.name, 
 c.telephone, 
 (CASE WHEN pm.status = 1 THEN 'Plus' ELSE 'Regular' END) AS membership
FROM customer AS c
LEFT JOIN plus_membership AS pm 
  ON pm.customer_id = c.customer_id 

另一种方法可以使用 Correlated Subquery and Exists()。通常,这种 比左连接方法 效率低。

SELECT 
  c.customer_id, 
  c.name, 
  c.telephone, 
  CASE WHEN EXISTS (SELECT 1 
                    FROM plus_membership AS pm 
                    WHERE pm.customer_id = c.customer_id AND 
                          pm.status = 1
                   )
       THEN 'Plus' 
       ELSE 'Regular' 
  END AS membership 
FROM customer AS c

我们使用EXISTSIN在另一个table中查找数据。

select customer_id, name, telephone,
  case when customer_id in (select customer_id from plus_membership where status = 1)
       then 'Plus' else 'Regular' end as membership
from customer
order by customer_id;