MySQL在多个表中选择不同的值

时间:2010-05-06 07:36:37

标签: mysql select distinct

我有两张桌子:

table_1
uid | xid | name

table_2
uid | elements | time | pkey

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

uid,table_1中的xid是唯一的,table_1和table_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!

1 个答案:

答案 0 :(得分:1)

这是我的解决方案。我认为,不仅仅是提供有效的查询,我将逐步完成我的思考过程以及我在每一步中尝试的查询:

首先,让我们为不同的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()聚合函数,这将更加简单。不幸的是,事实并非如此,我们必须解决子查询,order-by,限制组合。

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)

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

相关问题