2

我有一个这样的父表

    ID    |   ParentTestID    |   TestID
----------------------------------------
    1     |        10         |    15
    2     |        10         |    25
    3     |        10         |    35

第二张表

ID    |   TestID    |   TestName    |   LanguageID
-----------------------------------------
1     |   15         |    Test1      |      8  
2     |   15         |    Test2      |      3  
3     |   15         |    Test3      |      1  
4     |   25         |    Test1      |      5  
5     |   25         |    Test2      |      3  
6     |   25         |    Test3      |      4  
7     |   35         |    Test1      |      3  
8     |   35         |    Test2      |      8  
9     |   35         |    Test3      |      9  

我的方案是当我只知道第一个表上的 ParentTestID 时,从第二个表中找到公共语言 ID

这意味着如果我知道父 TestID 10,则结果将为 3,因为 10 以下的所有 testID 具有共同语言 ID 3

此外,父 ID 下的 testID 数量是不可预测的。它不会只有 3。

我正在寻找没有光标或此类并发症的查询。

4

2 回答 2

3
SELECT b.LanguageID
FROM    firstTable a
        INNER JOIN secondTable b    
            ON a.TestID = b.TestID
WHERE   a.ParentTestID = 10
GROUP   BY b.languageID
HAVING  COUNT(DISTINCT b.TestID) =
        (
          SELECT COUNT(c.testid) 
          FROM   firsttable c 
          WHERE  c.parenttestid = 10
        )

在该行中,如果对每个 都是唯一的HAVING COUNT(DISTINCT b.TestID),则不需要使用DISTINCT关键字。LanguageIDTestID

于 2013-07-17T13:25:27.173 回答
0

tests假设每个只有 3个parenttestid,您可以尝试以下查询:

select distinct languageid
from child
where testid in (select testid from parent where parenttestid = 10)
group by languageid having count(*) > 2

编辑:

如果计数不固定,则此查询将起作用:

select distinct languageid
from child
where testid in (select testid from parent where parenttestid = 10)
group by languageid
having count(testid) = (select count(testid) from parent where parenttestid = 10)
于 2013-07-17T13:31:24.743 回答