繁体   English   中英

MySQL跨多个表选择不同的值

[英]MySQL Select distinct values across multiple tables

我有两个表:

table_1
uid | xid | name

table_2
uid | elements | time | pkey

我想选择xid,元素和时间的多行,其中time是10个最小值,而uid(或xid)是不同的。

uid,表_1中的xid是唯一的,并且表_1和表_2中的uid之间是一对多的关系。

我尝试了类似的方法,但是效果不是很好:

SELECT table_1.xid, MIN(table_2.time), table_2.elements
FROM table_1, table_2
WHERE table_1.uid= table_2.uid
GROUP BY table_2.uid
LIMIT 10

让我们来研究一些数据:

table_1
uid | xid | name
1 | 435 | John
2 | 596 | Jane


table_2
uid | elements | time | pkey
1 | 1 | 567 | 0
2 | 2 | 335 | 1
1 | 1 | 435 | 2
1 | 2 | 456 | 3
2 | 1 | 337 | 4
1 | 1 | 428 | 5

如何选择每个UID的前2个不同结果? 在这种情况下:

fid| elements | time
596| 2 | 335
435| 1 | 428

谢谢!!!

如果人们不理解为什么lexu的解决方案不起作用-它不绑定到表2上的主键

如果我将以上数据更改为:

table_2
uid | elements | time | pkey
1 | 1 | 567 | 0
2 | 2 | 335 | 1
1 | 1 | 435 | 2
1 | 2 | 456 | 3
2 | 1 | 337 | 4
1 | 2 | 428 | 5

保持table_1不变,则结果应为:

fid| elements | time
596| 2 | 335
435| 2 | 428

但是使用@lexu的解决方案结果是:

fid| elements | time
596| 2 | 335
435| 1 | 428

但是,感谢大家的帮助,尤其是@eagle!

这是我的解决方案。 我认为,不只是给出有效的查询,而是将逐步介绍我的思考过程以及在每个步骤中尝试的查询:

首先,让我们为不同的uid选择最小的10次:

select uid, min(time)
from table_2
group by uid
order by 2
limit 10

这给我们:

uid | time
2 | 335
1 | 428

这很容易...很遗憾,这不允许我们获取主键,如果添加以下行,将是一个问题:

table_2
uid | elements | time | pkey
1 | 2 | 428 | 6

在将来的查询中,当我们尝试连接timeuid ,我们将获得两条记录而不是1条记录。因此,我们需要一个更好的查询,该查询返回一个不同的值(例如pkey),而不是time ,我假设它可以是不明显...

注意:如果MySQL具有FIRST()LAST()聚合函数,这将更加简单。 不幸的是,事实并非如此,因此我们必须满足子查询,按订单,限制组合的要求。

select
  t2.uid,
  (select pkey from table_2 t3 where t2.uid = t3.uid order by t3.time asc limit 1) as minpkey
from
  (select uid, min(time) from table_2 group by uid order by 2 limit 10) t2

现在将返回我们可以使用的结果:

uid | minpkey
1 | 5
2 | 1

请注意,随机选择了5个,而6个选择起来同样容易。 这一切都取决于mysql决定如何选择它。 但是对我们而言,这并不重要。

接下来,我们要显示更多数据(即xidelements字段):

select t1.xid as fid, t5.elements, t5.time
from 
(select
  t2.uid,
  (select pkey from table_2 t3 where t2.uid = t3.uid order by t3.time asc limit 1) as minpkey
from
  (select uid, min(time) from table_2 group by uid order by 2 limit 10) t2
) t4
inner join table_1 t1 on (t4.uid = t1.uid)
inner join table_2 t5 on (t4.minpkey = t5.pkey)

而且中提琴,它应该返回您在示例中提供的完全相同的数据! 它可能不是很有效,但是应该可以!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM