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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.