【问题标题】:Fetch Data from master table based on child table condition in sql serversql server 根据子表条件从主表中获取数据
【发布时间】:2014-04-09 11:29:31
【问题描述】:

需要根据子表条件从主表中获取数据。

主表:-

ID Name Address

1   abc   xyz
2   abs   txt
3   aui   tre
4   pop   top
5   the   tre
6   pot   tos
7   pog   sop
8   pat   top
9   bat   cric
10  not   kot

子表:-

chid shootid imagename       IDFK
101   234    123ab.jpg        3
102   234    54abcab.jpg      3
103   235    123abc.jpg       3
104   236    12390acb.jpg     Null
105   235    12332aab.jpg     8
106   234    123786ab.jpg     4
107   234    54789abcab.jpg   10
108   235    122343abc.jpg    10
109   235    122123acb.jpg    4
110   234    12123aab.jpg     9
111   234    1223ab.jpg       Null
112   233    5432abcab.jpg    Null
113   235    1239abc.jpg      Null
114   236    1238acb.jpg      2
115   236    12356aab.jpg     2
116   236    1235ab.jpg       2
117   236    545abcab.jpg     Null
118   237    1233abc.jpg      1
119   237    1223acb.jpg      1
120   237    1123aab.jpg      1

子表IDFK是外键,主表ID是主键。 现在我想从主表中显示那些在像where childtable.Shootid=234 这样的shootid 上的子表过滤器中不存在的名称。我试过了,但没有找到想要的输出。每次返回的结果都是一样的,因为不同的 shootid 也是一样的。

请帮助我并告诉我正确的查询。

【问题讨论】:

  • 请使用您提供的示例表中的行添加所需的输出。您有多个用于拍摄 234 的 IDFK 值,您是否尝试从 Master 获取与这些值对应的行,或者不对应于这些值的行?

标签: mysql sql-server


【解决方案1】:

我不知道我是否理解你,但我认为这就是你想要的,

Select * from [master] m
where m.ID not in (Select IDFK from detail where shootid=234)

【讨论】:

  • 你能写出你想要的输出吗
【解决方案2】:

我想这就是你要找的。​​p>

 Select distinct m.name from master m LEFT OUTER JOIN child c
     ON m.id = c.id and 
        c.shootid=234    
    where 
     c.id is null  

【讨论】:

  • 很抱歉没有给我想要的输出,我也试过这种方式。
猜你喜欢
  • 2016-01-17
  • 2020-09-24
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多