简体   繁体   中英

Creating a multi-row “table” as part of a SELECT

I'm not really sure how to describe my question (thus the awful title), but it's related to this recent question .

The problem would be easily solved if there was some way for me to create a "table" with 4 rows as part of my SELECT (to use with NOT IN or MINUS).

What I mean is, I can do this:

SELECT 1, 2, 3, 4;

And will receive one row from the database:

| 1 | 2 | 3 | 4 |

But is there any way to receive the following (without using UNION, I don't really want a query that's potentially thousands of lines long with a long list)?

| 1 |
| 2 |
| 3 |
| 4 |

This kind of query is possible in databases that support recursive queries (postgres, oracle, db2, mssql to name a few).

In mysql your (conceptually) easiest path would be to do create temporary table and then insert the IDs you are interested in as suggested here

If you want it nicer, you could put the create temp table in mysql stored procedure .

The best way I've found to split a delimited constant input into a table is using a numbers / tally table - see http://www.sqlteam.com/article/parsing-csv-values-into-multiple-rows for more info. I've used this technique before on large datasets and found it pretty fast.

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