Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 显示id并计数相同的外键_Mysql_Sql - Fatal编程技术网

Mysql 显示id并计数相同的外键

Mysql 显示id并计数相同的外键,mysql,sql,Mysql,Sql,我正在使用MySql。我有一个表,有两列id主键和外键id_。id的数量可以与的id_相同。我想获取所有id,并获取id_与id相关的行数。如何进行此sql查询?到目前为止,我只能得到这个: 选择id,从test_表中选择COUNTid_作为test_表中的count 数据库的表: 我想要的结果是: 你可以试试这个 ; with cte as ( select distinct id_of, count(*) as Coun from testtable ) select t.id ,

我正在使用MySql。我有一个表,有两列id主键和外键id_。id的数量可以与的id_相同。我想获取所有id,并获取id_与id相关的行数。如何进行此sql查询?到目前为止,我只能得到这个:

选择id,从test_表中选择COUNTid_作为test_表中的count

数据库的表:

我想要的结果是:

你可以试试这个

  ; with cte as ( select distinct id_of, count(*) as Coun from testtable )
  select t.id , c.coun from testtable as t inner join cte as c on t.id_of=c.id_of
您可以尝试以下方法:

select id , count(*) over (partition by id_of) id_of from Yourtable

只需要对你的问题稍加更正

  SELECT id, 
 (SELECT COUNT(*) FROM test_table t2 where t2.id_of=t1.id_of) AS count
  FROM test_table t1

你可以在subqiery上使用ajoin进行计数

select  a.id, t.count_of_id_of 
from test_table a 
inner join     (
  select  id_of, count(*)  count_of_id_of
  from  test_table 
  group by id_of 
) t on t.id_of= a.id_of

标记您的dbms名称问题已更新这里是@AmandepSingh
  SELECT id, 
 (SELECT COUNT(*) FROM test_table t2 where t2.id_of=t1.id_of) AS count
  FROM test_table t1
select  a.id, t.count_of_id_of 
from test_table a 
inner join     (
  select  id_of, count(*)  count_of_id_of
  from  test_table 
  group by id_of 
) t on t.id_of= a.id_of