如何对 MySQL 中的列进行分组并消除重复出现的 ID?

发布于 2024-10-19 03:31:26 字数 705 浏览 3 评论 0原文

MySQL

+-----+-----+
| id1 | id2 |
+-----+-----+
|  1  |  1  |
+-----+-----+
|  1  |  1  |
+-----+-----+
|  1  |  2  |
+-----+-----+
|  2  |  1  |
+-----+-----+

PHP

$a = mysql_query("SELECT id1, COUNT(id2) AS count FROM table GROUP BY id1");
while($b = mysql_fetch_assoc($a))
{
    echo 'id1: '.$b['id1'].' | count: '.$b['count'].'<br />';
}

输出:

id1: 1 | count: 3
id1: 2 | count: 1

但是如何删除每个 id1 的 id2 列中重复出现的数字?例如,id1为1的计数应该是2而不是3,因为我只想对id2中的1计数一次,而不是两次。

所以,输出实际上应该是:

id1: 1 | count: 2
id1: 2 | count: 1

我希望这是有道理的。

MySQL

+-----+-----+
| id1 | id2 |
+-----+-----+
|  1  |  1  |
+-----+-----+
|  1  |  1  |
+-----+-----+
|  1  |  2  |
+-----+-----+
|  2  |  1  |
+-----+-----+

PHP

$a = mysql_query("SELECT id1, COUNT(id2) AS count FROM table GROUP BY id1");
while($b = mysql_fetch_assoc($a))
{
    echo 'id1: '.$b['id1'].' | count: '.$b['count'].'<br />';
}

Output:

id1: 1 | count: 3
id1: 2 | count: 1

But how do I remove recurring numbers in the column id2 for each id1? For example, the count where id1 is 1 should be 2 instead of 3, because I want to count the 1 in id2 only once, and not twice.

So, the output should actually be:

id1: 1 | count: 2
id1: 2 | count: 1

I hope this makes sense.

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

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

发布评论

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

评论(3

红衣飘飘貌似仙 2024-10-26 03:31:26

选择 id1, COUNT(DISTINCT id2) ...

SELECT id1, COUNT(DISTINCT id2) ...

給妳壹絲溫柔 2024-10-26 03:31:26
SELECT id1, COUNT(DISTINCT id2) AS count FROM table GROUP BY id1
SELECT id1, COUNT(DISTINCT id2) AS count FROM table GROUP BY id1
树深时见影 2024-10-26 03:31:26

使用子查询:

SELECT 
  t.id1,COUNT(t.id2) AS count
FROM
  (SELECT DISTINCT id1,id2 FROM table) as t
GROUP BY 
  t.id1

Use a subquery:

SELECT 
  t.id1,COUNT(t.id2) AS count
FROM
  (SELECT DISTINCT id1,id2 FROM table) as t
GROUP BY 
  t.id1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文