开发者

mySQL - select unique values in two columns

开发者 https://www.devze.com 2023-04-10 02:36 出处:网络
I really can\'t find a simple or even any solution via sql to get unique data from DB (mySQL). I will give a sample (simplified):

I really can't find a simple or even any solution via sql to get unique data from DB (mySQL).

I will give a sample (simplified):

TABLE t

fruit  | color  | weight
-----------------------
apple  | red    | 34
kiwi   | red    | 23
banana | yellow | 100
kiwi   | black  | 3567
apple  | yellow | 23
banana | green  | 2345
pear   | green  | 1900

And now I want output - something like distinct(apple) and distinct(color) together and order by weight desc:

kiwi   | black  | 3567
banana | green  | 2345
apple  | red    | 34
  • pear | green // is not ok, be开发者_运维问答couse green is already "used"
  • banana | yellow // is not ok, becouse banana is already "used"

So I need not only group by fruit, but also color (all unique).

Any advice or solution? Thanks!


I'm not clear why banana|green is preferred to banana|yellow (change RIGHT JOIN to INNER JOIN for tastier fruit) so I hope I've understood what you're trying to do:

SELECT t1.fruit, t1.color, t1.weight
FROM
t AS t1
RIGHT JOIN
(
SELECT fruit, color, weight
FROM t
GROUP BY 
color
) AS t2
ON
t1.fruit = t2.fruit AND t1.color = t2.color
GROUP BY fruit
ORDER BY weight DESC;

Also please be aware how MySQL handles hidden columns in GROUP BY.


SELECT fruit, color, weight 
FROM t
GROUP BY fruit, color
HAVING COUNT(*) = 1
ORDER BY weight DESC
0

精彩评论

暂无评论...
验证码 换一张
取 消