Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE col1,col2 IN (...) [SQL subquery using composite primary key]

Given a table foo with a composite primary key (a,b), is there a legal syntax for writing a query such as:

SELECT ... FROM foo WHERE a,b IN (SELECT ...many tuples of a/b values...); UPDATE foo SET ... WHERE a,b IN (SELECT ...many tuples of a/b values...); 

If this is not possible, and you could not modify the schema, how could you perform the equivalent of the above?

I'm also going to put the terms "compound primary key", "subselect", "sub-select", and "sub-query" here for search hits on these aliases.

Edit: I'm interested in answers for standard SQL as well as those that would work with PostgreSQL and SQLite 3.

like image 813
Phrogz Avatar asked Jan 07 '11 04:01

Phrogz


People also ask

How do I query a composite primary key in SQL?

A composite key is made by the combination of two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined uniqueness of a row is guaranteed, but when it is taken individually it does not guarantee uniqueness, or it can also be understood as a primary key made ...

Can you use a subquery in a where clause?

Subqueries in the WHERE Clause. A subquery in a WHERE clause can be used to qualify a column against a set of rows. For example, the following subquery returns the department numbers for departments on the third floor. The outer query retrieves the names of employees who work on the third floor.

Can we insert NULL values in composite primary key?

In composite primary key columns you cannot pass null values.

How do I add a composite primary key to an existing table in SQL?

Now, you can execute the ALTER TABLE statement to add a MySQL Composite Primary key as follows: mysql> alter table Orders ADD PRIMARY KEY (order_id, product_id);


1 Answers

sqlite> create table foo (a,b,c); sqlite> create table bar (x,y); sqlite> select * from foo where exists (select 1 from bar where foo.a = bar.x and foo.b = bar.y); 

Replace the select 1 from bar with your select ... many tuples of a/b values ....

Or create a temporary table of your select ... many tuples of a/b values ... and use it in place of bar..

like image 51
Doug Currie Avatar answered Sep 19 '22 13:09

Doug Currie