MYSQL - 如何创建单个查询来完成此任务

时间:2016-11-30 22:26:32

标签: mysql

我有一个相当复杂的情况,我想看看是否有一个查询我可以用来获取数据。

在下面的伪代码中,假设" *"在每个select子句中都选择了相应的列,table3和table4具有足够相似的列,我可以用padding / fake列处理差异。

select * from table1 where ActiveFlag=1
for each row returned (as A)
 //check if member has a record in membership table
 select * from table2 where MembershipId=A.MembershipId
 if (row exists)
   select * from table3 where MemberId=A.MemberId
 else
   select * from table4 where MembershipId=A.MembershipId
end of for loop

1 个答案:

答案 0 :(得分:0)

这个假设TableA中的每一行都可以有0-1个成员资格,否则我们需要首先过滤重复项。

 SELECT CASE WHEN M.MembershipId IS NULL 
             THEN T4.field1
             ELSE T3.field1
        END as field1,
        ....
        CASE WHEN M.MembershipId IS NULL 
             THEN T4.fieldN
             ELSE T3.fieldN
        END as fieldN

 FROM TableA A 
 LEFT JOIN Membership M
   ON A.MembershipId = M.MembershipId
 CROSS JOIN table3 T3
 CROSS JOIN table4 T4
 WHERE A.MemberId = T3.MemberId
    OR A.MembershipId = T4.MembershipId

如果您有重复的成员资格,请使用类似的内容替换前两个JOIN。

FROM (
       SELECT DISTINCT TableA.*, M.MembershipId
       FROM TableA A 
       LEFT JOIN Membership M
         ON A.MembershipId = M.MembershipId
     ) A
CROSS JOIN ..