简体   繁体   English

由于使用子查询将查询重写为使用联接的查询而导致的SQL错误

[英]SQL error as a result of rewriting a query using subquery into a query using join

The original query: 原始查询:

SELECT      o.offering_number,
        o.english_description,
        o.french_description,
        fop.price_amount,
        fop.price_type_code,
        fop.price_status_code,
        fop.offering_id,
        (SELECT fop1.price_amount from facility_offering_price fop1
                WHERE fop.offering_id = fop1.Offering_Id
                    AND fop1.price_type_code = 5
                AND fop1.price_status_code = 3
            ) as 'priceAmount'
            from facility_offering_price fop
            join offering o on fop.offering_id = o.offering_id
                WHERE fop.price_start_date = '15-10-28'
                AND fop.price_status_code IN (1,2)
                /*AND (price_status_code IS NULL)*/
                AND fop.price_type_code = 5
                /*AND (o.offering_number IS NULL)*/
                    ORDER BY o.offering_number ASC, fop.price_sequence_number ASC;

It produces a result of one entry. 它产生一次输入的结果。

The result query: 结果查询:

SELECT      o.offering_number,
        o.english_description,
        o.french_description,
        fop.price_amount,
        fop2.price_amount,
        fop.price_type_code,
        fop.offering_id,
        fop2.offering_id
            from facility_offering_price fop
            join offering o on fop.offering_id = o.offering_id
            inner join
                (select
                    fop1.offering_id,
                    fop1.price_amount
                            from facility_offering_price fop1
                            WHERE fop1.price_type_code = 5
                            AND fop1.price_status_code = 3
                ) fop2 on fop.offering_id = fop2.offering_id
                WHERE fop.price_start_date = '15-10-28'
                AND fop.price_status_code IN (1,2)
                /*AND (price_status_code IS NULL)*/
                AND fop.price_type_code = 5
                /*AND (o.offering_number IS NULL)*/
                    ORDER BY o.offering_number ASC, fop.price_sequence_number ASC;

It's result set is empty. 结果集为空。 However, an entry is found if I ask for fop1.price_status_code = 1. 但是,如果我要求fop1.price_status_code = 1,则会找到一个条目。

Unable to wrap my head around this one I would appreciate your help. 无法绕过我的头,谢谢您的帮助。

Try using LEFT JOIN instead. 尝试改用LEFT JOIN The conversion from SELECT a, subquery AS val FROM ... to a join is more accurately reflected that way. SELECT a, subquery AS val FROM ...SELECT a, subquery AS val FROM ...的转换更准确地反映了这种方式。 The original query would return rows with NULL val when the subquery has no results; 当子查询没有结果时,原始查询将返回NULL val行。 your version ends up omitting such rows completely. 您的版本最终完全忽略了这些行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM