使用子查询将OUTER APPLY重写为Redshift

时间:2018-10-29 07:45:04

标签: sql amazon-redshift lateral-join

我重写sql服务器脚本以重新转移数据库查询

我有OUTER APPLY结构

var purHeader = data.ToObject<PurHeader>();
var purDetails = data["items"].ToObject<PurDetail[]>();

但是Redshift没有外部应用。如何使用LEFT JOIN正确重写它?

更新

我想像这样重写它

OUTER APPLY
   (
   SELECT  q.*
   FROM    (
           SELECT  ROW_NUMBER() OVER(ORDER BY ca.Id DESC) AS rn,
                   ca.StateProvince,
                   ca.ZipPostalCode,
                   ca.ContactId
           FROM    public.contact_addresses ca 
           WHERE   ca.OrganizationId = <Parameters.DemographicsOrgId>
                   AND ca.DeletedDate IS NULL
                   AND ca.TypeId = 7
                   AND ca.ContactId = cc.Id
           ) q
   WHERE   q.rn = 1
   ) ca

但这是正确的吗?

2 个答案:

答案 0 :(得分:3)

不,它看起来不正确。我猜:

const updateMessage = (userId, messageId) => {
    return OperationMessageUser.findOneAndUpdate({
        userId: userId,
        'messages.messageId': {
            $ne: messageId
        },
    }, {
        $addToSet: {
            messages: {
                messageId: messageId,
                status: 1,
                lastRead: Date.now()
            },
        },
    }, {
        new: true,
        //projection: 'messages',
    });
};

基本上,您需要按相关条件(如果它们相等)进行汇总,然后将其用于外部LEFT JOIN (SELECT ca.OrganizationId, ROW_NUMBER() OVER (ORDER BY ca.Id DESC) AS rn, ca.StateProvince, ca.ZipPostalCode, ca.ContactId FROM public.contact_addresses ca WHERE ca.DeletedDate IS NULL AND ca.TypeId = 7 GROUP BY ca.OrganizationId, ca.ContactId ) ca ON ca.ContactId = cc.ID AND ca.OrganizationId = <Parameters.DemographicsOrgId> AND ca.rn = 1 条件。

答案 1 :(得分:2)

OUTER APPLY运算符返回左表表达式中的所有行,无论其与右表表达式的匹配如何。对于右表表达式中没有对应匹配项的那些行,右表表达式的列中包含NULL值

所以您的方法是正确的