简体   繁体   中英

sub-query substitution in sqlite query

I am new to SQLite and SQL. I was playing with a few nested queries and found that I was repeatedly using some subqueries. I wanted to know if there is any way to simplify the queries for better readability. Consider the following query.

SELECT *
FROM
    table1
INNER JOIN
(
    SELECT *
    FROM
        table2
    WHERE
        col1=1234
) t
ON table1.col3=t.col5

I wanted to simplify this by something equivalent to the following (in C macro syntax):

#define MYMACRO(X) SELECT * FROM table2 WHERE col1=X
SELECT * FROM table1 INNER JOIN MYMACRO(1234) t ON table1.col3=t.col5

Is this possible ?

Note : I know I can simplify the first query so that it would not be nested. I am just using it for explaining my question.

WITH is the keyword you're looking for.

With MyMacro AS SELECT * FROM table2 WHERE col1=@parameter

SELECT * FROM table1 INNER JOIN MyMacro ON table1.col3=MyMacro.col5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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