的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
我希望这是有道理的。
答案 0 :(得分:1)
SELECT id1, COUNT(DISTINCT id2) ...
答案 1 :(得分:0)
SELECT id1, COUNT(DISTINCT id2) AS count FROM table GROUP BY id1
答案 2 :(得分:0)
使用子查询:
SELECT
t.id1,COUNT(t.id2) AS count
FROM
(SELECT DISTINCT id1,id2 FROM table) as t
GROUP BY
t.id1