【问题标题】:Intersected or Common values of different queries based on values from Another Query基于来自另一个查询的值的不同查询的相交或公共值
【发布时间】:2013-07-17 13:15:18
【问题描述】:

我有一个这样的父表

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

我正在寻找没有光标或此类复杂问题的查询。

【问题讨论】:

  • common languageID 的意思是 ID 存在于同一 ParentID 的所有 TestID 中?
  • 您的结果只是一个计数,参数是@ParentTestID ?
  • @491243 LanguageID in 用于第二个表中的每个测试。测试名称会有所不同。例如:TestSpanish (LangID 8) , TestFrench(LangID 3), TestEnglish (LanguageID 1) 所以这些测试名称会有所不同所以我的要求是找到所有具有 Common LanguageID 为 3的测试>
  • @TimSchmelter No.. 它不会总是单行元素。如果testIDs有多个公共语言ID,它将是多行是的。唯一的参数是ParentTestID

标签: sql sql-server-2008 intersection


【解决方案1】:
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) 行中,如果LanguageID 对于每个TestID 都是唯一的,则不需要使用DISTINCT 关键字。

【讨论】:

  • 您可以通过删除子查询中的联接来简化查询。
  • @GordonLinoff 是的,我可以删除它,但如果我要删除子查询中的连接,我怎么知道TestID 是否来自特定的ParentTestID
  • 你可以这样做:select count(c.testid) from firsttable c where c.parenttestid = 10.
  • @491243 你太棒了。它工作得很好。但是有什么简化的范围吗?
  • @sforsandeep 请参阅 Gordon 的评论。
【解决方案2】:

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

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)

【讨论】:

  • 我们无法预测这样的事情。它总是会变化的。
  • @sforsandeep,请检查编辑。这似乎符合您的要求。
  • OK.. 这会起作用.. 但请检查标记为答案的那个。这比多个子查询更清楚
猜你喜欢
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
相关资源
最近更新 更多