我有一个带有整数id(PK)的clubMembers表
我还有另一张桌子,上面列出了几个ids(俱乐部的终身成员)
我想创建一个包含所有clubMembers的视图,以及一个计算其成员类型的额外列,其工作方式如下:
if (clubMember.id is in lifeMembers) result = "Life"
elseif (clubMember.dateJoinedClub is over 1 year ago) result = "Full"
else result = "Probationary"
但我不知道如何在SQL中做到这一点。
答案 0 :(得分:3)
使用LEFT JOIN
和CASE
,如下所示:
SELECT cm.*,
CASE WHEN lm.id IS NOT NULL THEN 'Life'
WHEN now() > DATE_ADD(cm.dateJoinedClub, INTERVAL 1 YEAR) THEN 'Full'
ELSE 'Probationary'
END AS `result`
FROM clubMembers cm
LEFT JOIN lifeMembers lm
ON cm.id = lm.id
答案 1 :(得分:0)
在LEFT JOIN
上执行lifeMembers
,然后使用IF
来获取result
:
IF(lifeMembers.id IS NOT NULL, "Life", IF(clubMember.dateJoinedClub < NOW() - INTERVAL 1 YEAR, "Full", "Probationary")) AS res
答案 2 :(得分:0)
使用'case'作为视图中额外列的定义:
case when (clubMember.id in (select clubMemberId from lifeMembers)) then 'Life'
when (clubMember.dateJoinedClub < (NOW() - INTERVAL 1 YEAR)) then 'Full'
else 'Probationary' end as ExtraColumn