简体   繁体   中英

can IN be used on a sql ON clause

Can IN be used on a sql ON clause using MySQL? if so, is it considered bad practice to do so? Are there any reasons not to do either the OR or IN, and instead JOIN t3 twice to both t1 and t2?

SELECT *
FROM t1
LEFT OUTER JOIN t2 ON t2.t1_id=t1.id
LEFT OUTER JOIN t3 ON t3.fk=t1.id OR t3.fk=t2.id
WHERE t3.id=123;

SELECT *
FROM t1
LEFT OUTER JOIN t2 ON t2.t1_id=t1.id
LEFT OUTER JOIN t3 ON t3.fk IN (t1.id,t2.id)
WHERE t3.id=123;

SELECT *
FROM t1
LEFT OUTER JOIN t2 ON t2.t1_id=t1.id
LEFT OUTER JOIN t3 AS t3a ON t3a.fk=t1.id
LEFT OUTER JOIN t3 AS t3b ON t3b.fk=t2.id
WHERE t3a.id=123 OR t3b.id=123;

Your three queries do not do the same thing.

The first two are equivalent, and there is no problem using in . I do find on clauses that use in with a subquery to be hard to understand, but with just a list of values or columns, they are often more readable then the equivalent or construct.

The third, however, is different. First, it has way more columns -- all the columns from t3a and t3b on each row. The first two only have one set of columns from t3 . And, if there is a match for both id s, the first two return rows for each match. The second only returns one rows (for a single match).

To answer your question simply from the MySQL docs :

The conditional_expr used with ON is any conditional expression of the form that can be used in a WHERE clause. Generally, you should use the ON clause for conditions that specify how to join tables, and the WHERE clause to restrict which rows you want in the result set.

Considering the usage of IN as acceptable practice is primarily opinion-based and cannot be answered succinctly. I don't see a problem with it but won't argue for its usage either.

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