开发者

"limit" clause on joining?

开发者 https://www.devze.com 2023-04-03 07:23 出处:网络
table1: id , otherColumn, otherColumn2 ... ta开发者_JS百科ble2: id, table1_id, someOtherColumns... I.E. one to many relationships

table1:

id , otherColumn, otherColumn2 ...

ta开发者_JS百科ble2:

id, table1_id, someOtherColumns...

I.E. one to many relationships

A trivial join would be:

select * from table1 left outer join table2 on table2.table1_id=table1.id;

I want to do something different: for each row in table1, bring at most 1 row from table2, no matter which if there are several candidates. Just as I can limit the amount of results on a regular select

Is this possible? How?


Possibilities:

  1. Use a sub-select. This will force the inner result-set to be limited. Advantage is that grouping/aggregation operations can be used. (I am not sure what issues, if any, MySQL has with sub-selects and holistic query planning.)

  2. Use a WHERE in the primary statement and let the SQL engine "do it's thing". If the WHERE can be "moved" before the join, a smart engine will do so as it will result in less rows being processed. I think this is part of the basic Relational Algebra model (for independent records), but I am not sure. Look at the query plan. (I do not use MySQL, so I do know what optimizations are done.)

And, as always, verify results and run performance tests if it matters.

Happy coding.

0

精彩评论

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

关注公众号