-3

table1:

id , otherColumn, otherColumn2 ...

table2:

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?

ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235
shealtiel
  • 8,020
  • 18
  • 50
  • 82

1 Answers1

1

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.