Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an inline SQL table on the fly (for an excluding left join)

Tags:

sql

mysql

rdbms

Let's assume the following:

Table A

id | value ---------- 1   | red 2   | orange 5   | yellow 10  | green 11  | blue 12  | indigo 20  | violet 

I have a list of id's (10, 11, 12, 13, 14) that can be used to look up id's in this table. This list of id's is generated in my frontend.

Using purely SQL, I need to select the id's from this list (10, 11, 12, 13, 14) that do not have entries in Table A (joining on the 'id' column). The result should be the resultset of id's 13 and 14.

How can I accomplish this using only SQL? (Also, I'd like to avoid using a stored procedure if possible)

The only approach I can think of is something that would create an inline SQL table on the fly to temporarily hold my list of id's. However, I have no idea how to do this. Is this possible? Is there a better way?

Thanks! :)

like image 782
rinogo Avatar asked May 22 '12 20:05

rinogo


People also ask

How do you except a row in SQL?

The SQL EXCEPT clause/operator is used to combine two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement. This means EXCEPT returns only rows, which are not available in the second SELECT statement.

What is inline table valued function?

The second type of user-defined function, the inline table-valued function, is similar to a view. Both are wrapped for a stored SELECT statement. An inline table-valued user-defined function retains the benefits of a view, and adds parameters.


2 Answers

You can do this from SQL Server 2008 onwards using a table value constructor.

SELECT * FROM (    VALUES(1, 'red'),          (2, 'orange'),          (5, 'yellow'),          (10, 'green'),          (11, 'blue'),          (12, 'indigo'),          (20, 'violet'))    AS Colors(Id, Value) 

More information here: Table Value Constructor

like image 57
phillip voyle Avatar answered Sep 18 '22 19:09

phillip voyle


You can create an "inline table" with a UNION subquery:

(             SELECT 10 AS id   UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14   -- etc. ) AS inline_table 
like image 45
eggyal Avatar answered Sep 19 '22 19:09

eggyal