使用带有计数的 MYSQL Distinct?

发布于 2024-12-05 14:25:26 字数 360 浏览 2 评论 0原文

我希望在 MySQL 查询中同时使用 DISTINCT 和 COUNT,如下所示:

SELECT DISTINCT `data1` AS new_data, COUNT(new_data) FROM table_name WHERE `data2`='$data2' AND `data3` = '$data3'

目标是循环 DISTINCT 结果并对结果本身以及该结果的 COUNT 执行某些操作。

不幸的是,我对 MySQL 不太了解...

  1. 我不确定是否可以通过这种方式完成
  2. 是否有任何其他方法可以用来直接在 MySQL 中计算这一切,而无需多次数据库调用?

I'm looking to use both DISTINCT and COUNT in a MySQL query, something like this:

SELECT DISTINCT `data1` AS new_data, COUNT(new_data) FROM table_name WHERE `data2`='$data2' AND `data3` = '$data3'

The goal being to loop through the DISTINCT results and do something with both the result itself, as well as the COUNT for that result.

Unfortunately, I'm not too great with MySQL...

  1. I'm not sure if it can be done this way
  2. Is there any other approach that I could use to calculate this all directly in MySQL without multiple DB calls?

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

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

发布评论

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

评论(2

一抹微笑 2024-12-12 14:25:26

我假设您希望每个 data1 都有一个 count ,其中行符合您的条件。正确的?
按 data1 分组,就完成了:

SELECT `data1`, COUNT(*) 
FROM table_name 
WHERE `data2` = '$data2' AND `data3` = '$data3'
GROUP BY `data1`

I assume you want to have a count per data1 where rows match your conditions. Right?
Group by data1 and you're done:

SELECT `data1`, COUNT(*) 
FROM table_name 
WHERE `data2` = '$data2' AND `data3` = '$data3'
GROUP BY `data1`
心意如水 2024-12-12 14:25:26

我不确定你的问题...

你想做类似的事情吗?

SELECT COUNT(DISTINCT `data1`) AS new_data FROM table_name
WHERE `data2`='$data2' AND `data3` = '$data3'

I'm not sure to understand your question...

Do you want to do something like:

SELECT COUNT(DISTINCT `data1`) AS new_data FROM table_name
WHERE `data2`='$data2' AND `data3` = '$data3'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文