简体   繁体   English

如何选择两个不同的列?

[英]How do I SELECT two distinct columns?

I want to be able to select two distinct from col1 and col2 ordered by id.我希望能够从 id 排序的 col1 和 col2 中选择两个不同的。

I'm struggling to do this because when I write the following SQL query...我正在努力做到这一点,因为当我编写以下 SQL 查询时......

SELECT DISTINCT col1, col2
FROM table
ORDER BY id

I can't ORDER BY id because it's not in the SELECT statement but if I put id in the SELECT statement it will take the DISTINCT id, col1 and col2.我不能按 id 排序,因为它不在 SELECT 语句中,但是如果我将 id 放在 SELECT 语句中,它将采用 DISTINCT id、col1 和 col2。 Which is basically the whole table as it is since the id column is unique.这基本上是整个表,因为 id 列是唯一的。

How do I do this?我该怎么做呢?

您可以使用聚合,并在order by子句中放置一个聚合函数:

select col1, col2 from mytable group by col1, col2 order by min(id) limit 10

This is one way to do it:这是一种方法:

select A.col1, A.col2
from 
(select id, col1, col2
from Tablet
order by id) A
left join 
(select min(id) id2, col1, col2
from Tablet
GROUP BY COL1, COL2) B
on A.COL1 = B.COL1 AND A.COL2=b.COL2
where A.id = B.id2
LIMIT 4;

Here is the DEMO这是演示

If the task means "if there are duplicates by (col1, col2) then remove all such duplicates except one with the greatest id value", then如果任务的意思是“如果(col1, col2)有重复项(col1, col2)则删除除具有最大id值的重复项之外的所有此类重复项”,则

SELECT DISTINCT MAX(id) OVER (PARTITION BY col1, col2) id, col1, col2
FROM sourcetable
ORDER BY id DESC /* not sure in this point */
LIMIT 10

PS.附注。 Why "greatest"?为什么是“最大”? because of因为

So it should eliminate row 3 and NOT row 4 as it is duplicated.所以它应该消除第 3 行而不是第 4 行,因为它是重复的。

If the record with the least id value needed then replace MAX() to MIN().如果需要具有最小id值的记录,则将 MAX() 替换为 MIN()。

PPS.聚苯乙烯。 It seems the real task is "Show last 10 original messages from chat history".似乎真正的任务是“显示聊天记录中的最后 10 条原始消息”。

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

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