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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.