【问题标题】:query sql between two tables [duplicate]在两个表之间查询sql [重复]
【发布时间】:2017-09-21 14:59:25
【问题描述】:

我试过查询但没有搜索答案,我有两个表

我想在 Linq 中设计一个查询,获取所有在表 2 中注册的数据,其中值在数字字段 1 和值 3 和值 4 中,在这个例子中我得到表 1 的数据

感谢您的合作

【问题讨论】:

  • 为什么投反对票?

标签: sql linq sql-server-2012


【解决方案1】:

这就是我的做法 - 我用 SQL 编写它,因为我在这方面比在 LINQ 上要好得多,但是从一种转换到另一种应该很简单:

select 
    t1.id
    , t1.value
from table1 as t1
    inner join table2 as t21
        on t21.idTable1 = t1.id
        and t21.number = 1
    inner join table2 as t23
        on t23.idTable1 = t1.id
        and t23.number = 3
    inner join table2 as t24
        on t24.idTable1 = t1.id
        and t24.number = 4

这将三次连接到表 2 的子集,一次用于您想要的每个值。使用“内连接”使逻辑等效于 AND。

【讨论】:

    【解决方案2】:

    通过使用子查询

    select * from table_1 where id in (select idtable1 from table_2 where number in (1,3,4))

    按关节 select * from table_1 t1 join table_2 t2 on t1.id=t2.idtable1 where t2.number in (1,3,4)

    【讨论】:

      【解决方案3】:

      应该是

      select id,idTable1,number 
             from 
             table2 
       where idTable1 = 1
      

      如果我正确理解了这个问题。你的问题有点难以理解。如果应该在那里加入它的

         select b.id,a.Idtable1,a.number
           from table1 b ,table2 a 
           where b.id = a.Idtable1
      

      【讨论】:

        【解决方案4】:

        如果我没记错你想要什么,这可能会奏效。您需要加入 to 表,然后使用 where 检查您想要的条件。

        SELECT a.id, a.value
        FROM TABLE1 a
        INNER JOIN TABLE2 b on a.id=b.idTable1
        WHERE b.number in (1,3,4)
        AND a.id = 1;
        

        【讨论】:

        • 谢谢你的回答,但这是错误的,因为句子“in”,我获取数据只是为了满足一个条件,我想要获取具有编号 1 和其他寄存器在编号 3 和其他寄存器中的寄存器在值 4 中,我认为用句子“union”可以工作
        【解决方案5】:

        第一个查询假设 table2.number 对于给定的 id 是唯一的。那可能不是真的。如果是:

        select table1.id, table1.value
        from table1 
        join table2 
          on table1.id = table2.idTable1
        group by table1.id, table1.value
        having count(*) = 3
        where table2.number in (1,3,4)
        

        如果“数字”可能是一个重复值(对于每个 idTable1 来说不是唯一的),那么我们需要确保我们在 table2 中加入不同的值:

        select table1.id, table1.value
        from table1 
        join (select distinct table2.idTable1, table2.number where table2.number in (1,3,4)) t2 
          on table1.id = t2.idTable1
        group by table1.id, table1.value
        having count(*) = 3
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-14
          • 2010-12-14
          • 2011-01-05
          相关资源
          最近更新 更多