[英]How do I group columns in MySQL and get rid of recurring ids?
MySQL 的MySQL
+-----+-----+
| id1 | id2 |
+-----+-----+
| 1 | 1 |
+-----+-----+
| 1 | 1 |
+-----+-----+
| 1 | 2 |
+-----+-----+
| 2 | 1 |
+-----+-----+
PHP 的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? 但是,如何删除ID2列中每个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.
例如, id1为1的计数应为2而不是3,因为我只想对id2中的1进行一次计数,而不是两次。
So, the output should actually be: 因此,输出实际上应该是:
id1: 1 | count: 2
id1: 2 | count: 1
I hope this makes sense. 我希望这是有道理的。
SELECT id1, COUNT(DISTINCT id2) ...
SELECT id1, COUNT(DISTINCT id2) AS count FROM table GROUP BY 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.