我有一个这样的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,即仅显示1
或regular
,plus
表示处于plus
状态的客户是plus_membership
,如果客户在1
表中不存在,或者会员表中的状态不是plus_membership
,则为常规。例如:
1
答案 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 Subquery和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
答案 1 :(得分:1)
我们使用EXISTS
或IN
在另一个表中查找数据。
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;