MySQL使用两个表计算列

时间:2014-04-08 09:59:35

标签: mysql

我有一个带有整数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中做到这一点。

3 个答案:

答案 0 :(得分:3)

使用LEFT JOINCASE,如下所示:

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