tags:

views:

69

answers:

1

Just now I needed to do something like the following query, and was surprised that it actually worked as intented. However I cannot find any documentation on it so I'm a little afraid about unknown side effects of this. Here's what I wrote:

select * from Table1 where (col1, col2) in (select col3, col4 from Table2)

This seems to be matching a pair of columns against a list of column-pairs. Is this how it is supposed to work, or can I expect some nasty surprises down the road?

+5  A: 

It seems there is a page in the MySQL manual about that syntax : 12.2.9.5. Row Subqueries

One of the given examples is this one (quoting) :

SELECT column1,column2,column3
       FROM t1
       WHERE (column1,column2,column3) IN
             (SELECT column1,column2,column3 FROM t2);

Which is quite similar to your query.

So I suppose it is officially supported.


The same page says (quoting) :

Row constructors are legal in other contexts as well. For example, the following two statements are semantically equivalent (although the first one cannot be optimized until MySQL 5.0.26):

SELECT * FROM t1 WHERE (column1,column2) = (1,1);
SELECT * FROM t1 WHERE column1 = 1 AND column2 = 1;

So, even if the syntax you proposed is valid, the second one might be better, if you can use it, at least -- and more easy to read / understand ;-)
And you'll find plenty other stuff about subqueries from the page 12.2.9. Subquery Syntax


(Yeah, wasn't easy to find ^^ )

Pascal MARTIN
Yeah, subqueries, at least of this type, are part of the normal SQL standard I believe, so you shouldn't have to worry too much about portability this way.
Brent Nash
@Brent : I've actually **never** seen this syntax -- so I was quite curious about it too ^^ (and I've learned one more thing, answering questions on SO ! )
Pascal MARTIN
Whoa, yeah, that *is* buried deep down under! Thanks!
Vilx-
@Vilx : you're welcome ! And thanks to you for the interesting question !
Pascal MARTIN
He, the fun thing is that I *guessed* at it - and it worked! :D
Vilx-
@Pascal MARTIN - You're welcome too! :)
Vilx-