您好我有下表
------------------------------------------
| id | language | parentid | no_daughter |
------------------------------------------
| 1 | 1 | 0 | 2 |
------------------------------------------
| 1 | 1 | 0 | 2 |
------------------------------------------
| 2 | 1 | 1 | 1 |
------------------------------------------
| 2 | 2 | 1 | 1 |
------------------------------------------
| 3 | 1 | 1 | 0 |
------------------------------------------
| 3 | 2 | 1 | 0 |
------------------------------------------
| 4 | 1 | 2 | 0 |
------------------------------------------
| 4 | 2 | 2 | 0 |
------------------------------------------
| 5 | 1 | 2 | 0 |
------------------------------------------
| 5 | 2 | 2 | 1 |
-----------------------------------------
| 5 | 1 | 4 | 1 |
------------------------------------------
| 5 | 2 | 4 | 1 |
------------------------------------------
方案
每个记录在表中都有多行,具有不同的language
ID。 parentid
告诉谁是此记录的父级。 no_daughter
列告诉每条记录一条记录有多少子记录。理想情况下的均值如果no_daughter
的{{1}}值为2
,则表示id = 1
应为同一表中2条记录的1
。 但如果某个记录在语言方面有多个退出,则会将其视为一个记录。
我的问题
我需要找出那些parentid
值不正确的记录。这意味着如果no_daughter
为2,则必须有两个记录no_daughter
具有该ID。在上述案例中,parentid
的记录是有效的。但是id = 1
的记录无效,因为id = 2
但该记录的实际女儿是2. no_daughter = 1
任何机构都可以告诉我如何找到这些错误的记录?
在答案后更新
Ken Clark已经和shola给出了答案,返回相同的结果,例如shola查询
id=4
此查询返回那些在表格中某处被用作SELECT DISTINCT
id
FROM
tbl_info t
INNER JOIN
(SELECT
parentid,
COUNT(DISTINCT id) AS childs
FROM
tbl_info
GROUP BY parentid) AS parentchildrelation
ON t.id = parentchildrelation.parentid
AND t.no_daughters != parentchildrelation.childs
但具有错误parentid
值的ID。但是,不返回在no_daughter
列中具有价值但在表格中未被用作no_daugter
的ID。例如,parentid
有id = 5
,但在表格中未用作no_daughter = 1
。所以这也是一个错误的记录。但上面的查询并未捕获此类记录。
非常感谢任何帮助。
答案 0 :(得分:2)
试试这个:
SELECT DISTINCT
id
FROM
tbl_info t
Left JOIN
(SELECT
parentid,
COUNT(DISTINCT id) AS childs
FROM
tbl_info
GROUP BY parentid) AS parentchildrelation
ON t.id = parentchildrelation.parentid
Where t.no_daughters != parentchildrelation.childs
答案 1 :(得分:1)
试试这个:
SELECT id FROM tinfo t inner join
(SELECT parentid, COUNT(distinct language ) as childs FROM tinfo group by parentid) as summary
on t.id=summary.parentid and t.no_daughters!= summary.childs
答案 2 :(得分:1)
试试这个
Select Distinct * From tablename t
Left Join
(
Select COUNT(t1.Id) Doughter,t1.parentid,t1.language From tablename t1 Group By t1.parentid,t1.language
)tbl
On t.id=tbl.parentid And tbl.language=t.language And t.no_daughter<>tbl.Doughter