0

我有一个这样的 MySQL 表:

Id  Id_1    Id_2
1     0   0
2     0   0
3     1   0
4     1   0
5     0   0
6     0   1
7     2   1
8     0   2

其中 Id_1 和 Id_2 可以等于 Id 除了它自己或等于 0

我想通过使用最有效的查询来获得这个结果:

id    COUNT(Id_1)   COUNT(Id_2)
1         2             2
2         1             1
3         0             0
4         0             0
5         0             0
6         0             0
7         0             0
8         0             0

谢谢!

4

3 回答 3

0

您可以使用带有子查询的 CASE 语句来获得所需的结果

SELECT ID, SUM(id1.ids), SUM(id2.ids)
FROM mytable
 LEFT OUTER JOIN
  (SELECT id_1, count(id) ids
   FROM my table
   GROUP BY id_1) AS id1 ON mytable.ID = id1.id_1
 LEFT OUTER JOIN
  (SELECT id_2, count(id) ids
   FROM my table
   GROUP BY id_2) AS id2  AS id2 ON mytable.ID = id2.id_2
GROUP BY ID
ORDER BY ID
于 2013-03-07T14:34:21.467 回答
0

您的解释不是很清楚,但是根据您的示例数据和所需的输出,您可以通过两个外部连接到基表的子查询来完成此操作,如下所示:

select a.id, 
  coalesce(b.id_1_count,0), 
  coalesce(c.id_2_count,0)
from so15273831 a
left outer join (
  select id_1, count(*) as id_1_count
  from so15273831
  group by id_1
) b on b.id_1 = a.id
left outer join (
  select id_2, count(*) as id_2_count
  from so15273831
  group by id_2
) c on c.id_2 = a.id
order by a.id;

SQL 小提琴在这里:http ://sqlfiddle.com/#!2/71b67/1

于 2013-03-07T14:43:32.870 回答
0
Select t1.id1 id,
(Select COUNT(*) From tableName t2 Where t1.id1=t2.id2) COUNT(Id_1),
(Select COUNT(*) From tableName t2 Where t1.id1=t2.id3) COUNT(Id_2)
 From tableName t1

这是示例的替代方法:

declare @aa table
(
 id1 int,
 id2 int,
 id3 int

)

insert into @aa
Select 
1,0,0
Union All Select
2,0,0
Union All Select
3,1,0
Union All Select
4,1,0
Union All Select
5,0,0
Union All Select
6,0,1
Union All Select
7,2,1
Union All Select
8,0,2

 Select t1.id1,IsNull(t2.CountId,0) as [Count(Id_2)],IsNull(t3.CountId,0) as [Count(Id_2)] From @aa t1
 Left Join 
 (
  Select COUNT(*) CountId,t2.id2 From @aa t2 Group By t2.id2
 )t2
 On t1.id1=t2.id2
 Left Join 
 (
  Select COUNT(*) CountId,t2.id3 From @aa t2 Group By t2.id3
 )t3 On t1.id1=t3.id3
于 2013-03-07T14:44:35.290 回答