[英]MySQL select rows from left join with specific number of distinct values in one column but without total row limit
I have 2 tables (records, features) that are connected by one foreign key-relationship. 我有2个表(记录,功能),它们通过一个外键关系连接。
Now I want to draw samples from those two tables where in my primary table I select by an id which is the primary key. 现在,我想从这两个表中抽取样本,在这两个表中,我通过一个ID(即主键)进行选择。
So if I wanted to get all entries it would look like this: 因此,如果我想获取所有条目,它将如下所示:
SELECT features.record_id, [...more columns...]
FROM records
LEFT JOIN features ON records.id = features.record_id
ORDER BY records.id
What I try to achieve: 我想要达到的目标:
I would like to enhance the query so I can specify an exact number n of distinct values of records.record_id . 我想增强查询,以便可以指定records.record_id的不同值的确切数目n 。 I don't want n rows but all rows from the join until I have n diffferent record_id s without limiting the total number of rows in the most efficient way. 我不想要n行,而是想要连接中的所有行,直到我拥有n个不同的 record_id 为止,而没有以最有效的方式限制行的总数。 I hope this is understandable, if not: please tell me and I will try to elaborate my question. 我希望这是可以理解的,如果不是这样的话:请告诉我,我将尽力阐述我的问题。
To add additinal context: 要添加附加上下文:
I use this inside a java-program (plain jdbc) and my goal is to collect the information to build n fully populated record-objects in the most efficient way. 我在一个Java程序(纯jdbc)中使用了它,我的目标是收集信息以最有效的方式构建n个完全填充的记录对象。 I already tried drawing all data and iterate over the ordered result until I constructed a sufficient number of record-objects but it didn't turn out very efficient (already takes about half a minute for 100k entries). 我已经尝试绘制所有数据并遍历排序的结果,直到构造了足够数量的记录对象,但结果却不是很有效(100k条目已经花费了大约半分钟)。
You can limit the number of rows from records
with LIMIT
: 您可以使用LIMIT
records
的行数:
SELECT features.* FROM (
SELECT records.record_id
FROM records LIMIT 100
) t
LEFT JOIN features ON t.record_id = features.record_id
ORDER BY t.record_id
the column record_id
is the primary key so you don't need distinct
. 列record_id
是主键,因此您不需要distinct
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.