mySQL - 选择两列中的唯一值

发布于 2024-12-08 00:56:25 字数 606 浏览 0 评论 0原文

我真的找不到一个简单的解决方案,甚至无法通过 sql 找到任何解决方案来从数据库(mySQL)获取唯一的数据。

我将给出一个示例(简化的):

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

现在我想要输出 - 像不同(苹果)和不同(颜色)在一起并排序 重量描述:

kiwi   | black  | 3567
banana | green  | 2345
apple  | red    | 34
  • 梨 |绿色 // 不行,因为绿色已经“用过”
  • 香蕉 |黄色//不行,因为香蕉已经“使用”了,

所以我不仅需要按水果分组,还需要颜色(都是唯一的)。

有什么建议或解决方案吗?谢谢!

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, becouse 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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

毁梦 2024-12-15 00:56:25

我不清楚为什么banana|green比banana|yellow更受欢迎(将RIGHT JOIN更改为INNER JOIN以获得更美味的水果)所以我希望我已经理解你的意思了正在尝试这样做:

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;

另请注意MySQL如何处理隐藏GROUP BY 中的列

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.

北风几吹夏 2024-12-15 00:56:25
SELECT fruit, color, weight 
FROM t
GROUP BY fruit, color
HAVING COUNT(*) = 1
ORDER BY weight DESC
SELECT fruit, color, weight 
FROM t
GROUP BY fruit, color
HAVING COUNT(*) = 1
ORDER BY weight DESC
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文