1

你好,我有一个下表

------------------------------------------
| 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      |
------------------------------------------

设想

每条记录在表中都有多个具有不同languageID 的行。parentid告诉谁是该记录的父级。no_daughtercolumns 告诉每条记录一条记录有多少个子记录。理想情况下的意思 如果no_daughter值为2id = 1则表示1应该是parentid同一张表中的 2 条记录。但是,如果一个记录在语言方面有多个存在,它将被视为一个记录

我的问题

我需要找出那些no_daughter值不正确的记录。这意味着如果no_daughter为 2,则必须有两条记录谁parentid具有该 id。在上述情况下,记录id = 1是有效的。但是有记录id = 2是无效的,因为no_daughter = 1这个记录的实际女儿是 2。同样的情况是id=4

任何人都可以告诉我如何找到这些错误的记录吗?

回答后更新

Ken Clark 和 shola 给出了返回相同结果的答案,例如 shola 查询是

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在表中用作某处但具有错误no_daughter值的 id。no_daugter但不返回在列中具有值但未用作parentid表中任何位置的id 。例如id = 5no_daughter = 1但它没有像parentid表中那样使用。所以这也是一个错误的记录。但是上面的查询没有捕获这样的记录。

任何帮助都感激不尽。

4

3 回答 3

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 
于 2013-03-25T15:44:35.150 回答
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
于 2013-03-22T07:44:04.053 回答
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
于 2013-03-22T08:08:55.040 回答