开发者

Select from multiple tables with same condition, avoid ambiguity error

How can I do something like this but avoid the error column common_reference is ambiguous? I know it's ambiguous, I want to select from table_one all the results for common_ref开发者_如何学运维erence there, and table_two the same.

SELECT * FROM table_one, table_two WHERE common_reference = 42

This is obviously not going to work, so how do I use subqueries to achieve what I need?


Start with...

SELECT * FROM table_one, table_two WHERE table_one.common_reference = 42

...and continue this road:

SELECT * FROM table_one as T1, table_two as T2 WHERE T1.common_reference = 42


SELECT table_one.* FROM table_one, table_two WHERE table_one.common_reference = 42


MySQL will let you know via error if there is an unresolvable ambiguity in your SQL.

If you want to reference a specific field which also exists in another table (or the same table if you're doing a join on itself), use fully qualified fields

SELECT * FROM table_one, table_two WHERE table_one.common_reference = 42

and/or table alias's

SELECT * FROM table_one T1a, table_one T1b WHERE T1a.common_reference = 42

NB: Fair warning, as Mchl noted, these are Cartesian products and not typical joins.


As suggested by Mchl in the comments UNION was the solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜