[英]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
在將來的查詢中,當我們嘗試連接time
和uid
,我們將獲得兩條記錄而不是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決定如何選擇它。 但是對我們而言,這並不重要。
接下來,我們要顯示更多數據(即xid
和elements
字段):
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.