如何对 MySQL 中的列进行分组并消除重复出现的 ID?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
选择 id1, COUNT(DISTINCT id2) ...
SELECT id1, COUNT(DISTINCT id2) ...
使用子查询:
Use a subquery: