mysql忽略列,MySQL:使用DISTINCT时忽略选定的列

在SQL中,如果你想要查询表中列B和列C的唯一组合,但不想让列A作为区分条件,可以使用两种方法。一种是通过`GROUP BY`结合`MAX()`函数,只显示每个A、B组合的最大值的C;另一种是使用子查询,筛选出A、B组合的所有唯一记录。如果表中还有其他列,后者可能更为必要。
摘要由CSDN通过智能技术生成

Let's say:

I want to query colA, colB and colC in my table.

I want to see DISTINCT values but I don't want colA to be a criteria for distinction.

Omitting colA isn't an option.

What's the best way to structure that query?

解决方案

There are two cases here. Let's say you have the data

A B C (columns)

a b c1

a b c2

Taking distinct values of A, B gives just one result (a,b), with two values for column C.

So the question is do you want to see all values of C or just one value for each distinct value of columns A and B?

If you want to see just one value of C, then you can write

SELECT A, B, MAX(C) FROM YourTable

GROUP BY A, B

On the other hand, if you want to see all values for C then

SELECT DISTINCT A, B, C FROM YourTable WHERE ROW(A,B) IN

(SELECT A, B FROM YourTable

GROUP BY A, B)

gives you that. This last alternative is needed if there are other columns in the table.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值