“限制”加盟条款?
table1:
id , otherColumn, otherColumn2 ...
table2:
id, table1_id, someOtherColumns...
IE 一对多关系
一个简单的连接是:
select * from table1 left outer join table2 on table2.table1_id=table1.id;
我想做一些不同的事情:对于 table1 中的每一行,最多从 table2 中获取 1 行,无论是哪一行(如果有多个候选者)。正如我可以限制常规选择的结果数量
这可能吗?如何?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能性:
使用子选择。这将迫使内部结果集受到限制。优点是可以使用分组/聚合操作。 (我不确定 MySQL 在子选择和整体查询规划方面存在哪些问题(如果有)。)
在主语句中使用 WHERE,让 SQL 引擎“做它的事情”。如果 WHERE 可以在连接之前“移动”,智能引擎将会这样做,因为这将导致处理的行数减少。我认为这是基本关系代数模型的一部分(对于独立记录),但我不确定。查看查询计划。 (我不使用 MySQL,所以我知道做了哪些优化。)
并且,一如既往,验证结果并运行性能测试(如果重要)。
快乐编码。
Possibilities:
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.)
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.