在MySQL中使用自定义字符串创建别名列

时间:2018-11-05 09:26:50

标签: mysql join select alias

我有一个这样的MySQL表:

##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 |
+------------------+-----------+-------+------------+

以上结构中有两个表,第一个是customer,其中customer_id是主键,第二个是具有外键plus_membership的{​​{1}} ,customer_id表是一个表,用于在客户请求成为正成员的情况下显示请求,状态plus_membership表示该客户被批准为正成员。我需要选择客户表并添加别名列,假设别名列名称为Membership,即仅显示1regularplus表示处于plus状态的客户是plus_membership,如果客户在1表中不存在,或者会员表中的状态不是plus_membership,则为常规。例如:

1

2 个答案:

答案 0 :(得分:1)

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

Left Join将确保考虑customer表中的所有客户,无论他们在plus_membership表中是否有相应的匹配行。

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 SubqueryExists()。通常,此效率会比“左连接”方法低。

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

答案 1 :(得分:1)

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

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;