Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

mysql - Trying to get around lack of CTE

I'm having some issues filtering the results from a longer query I have.

Suppose we have three columns, with some sample rows:

# column_1, column_2, column_3

'value 1', 'value 2', null
'value 1', 'value 2', '2'
'value 2', 'value 2', null

I'd like to select all rows but exclude those where column_3 is null and its column_1, column_2 values are associated with at least one non-null column_3 value.

A pain point is that I'm stuck with MySQL 5.7, and these rows are produced by a pretty text-lengthy subquery. If I had CTEs I could do:

WITH 
    cte1 AS (...)
SELECT *
FROM cte1 as a
WHERE
    column_3 IS NOT NULL
    OR NOT EXISTS (
        SELECT 1
        FROM cte1 as b
        WHERE
            b.column_1 = a.column_1
            AND b.column_2 = a.column_2
            AND b.column_3 IS NOT NULL
    )

Is there some way I can do this without copy pasting the large subquery, given that I don't have access to CTEs?

question from:https://stackoverflow.com/questions/65894243/trying-to-get-around-lack-of-cte

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With or without CTE's, you would need to copy paste the large subquery. With would be:

with a as (subquery)
select *
from a
where ...

Without is even shorter:

select *
from (subquery) as a
where ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...