【问题标题】:MySQL single table subqueryMySQL单表子查询
【发布时间】:2015-02-13 17:56:08
【问题描述】:

我有一个问题,我希望使用col5=2206 获取表中的所有行,然后使用 col2 和 col3 选择所有其他行,其中包含与 col5 相同的 col2 和 col3 组合(示例中的 fi.低于 col2=2, col3=6)

我还希望将返回的行过滤为 col5 中具有特定值的行 (fi.col5=4000)。

('101', '2', '6', '2009-12-31', '2206', 'Exempt', '0', '0', '0', '4', '5'),  
('102', '2', '6', '2009-12-31', '4000', 'Exempt', '-1', '0', '0', '4', '5'),  
('103', '2', '6', '2009-12-31', '1200', '', '1', '0', '0', '4', '5');

我尝试过各种子查询语句。但是不能像在一张桌子上那样工作。这是可能的还是我需要创建一个更大的脚本。

【问题讨论】:

    标签: mysql subquery


    【解决方案1】:

    您使用自连接来实现您想要的。

     Select t2.*
       From table t1
       Join table t2 on ( t2.col2 = t1.col2 and t2.col3 = t1.col3 )
      Where t1.col5 = '2206'
        And t2.col5 <> '2206' -- replace that with specific filters like t2.col5 = '4000'
          ;
    

    【讨论】:

    • 非常感谢 - 这工作最快 - 只需要添加一个别名来制作第二行 From table t1 As t2.
    【解决方案2】:

    你最好使用 JOINS,但你需要子查询然后你可以试试这个:

    select a.* from table a where 
    a.col2 in (select col2  from table  where col5=a.col5) 
    and 
    a.col3 in (select col3  from table  where col5=a.col5) 
    and a.col5=4000;
    

    【讨论】:

      【解决方案3】:

      我宁愿建议您使用后端代码而不是 SQL 来执行此操作,因为它可能会给您带来性能问题。

      【讨论】:

      • 我宁愿不使用高度优化的db数据存储和查询引擎会导致性能下降。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多