开发者社区> 问答> 正文

在没有自联接表的情况下将单个列与多个值匹配

我想选择一个routing_id = 489的routing_id。

我使用SQL子查询,但会降低性能。

查询:

select routing_id 
from ec.production_autoroutingtag 
where tag_type = 'mounting_type' 
  AND tag_value='smd' 
  and routing_id in (select routing_id 
                     from ec.production_autoroutingtag 
                     where tag_type = 'x_ray' 
                       AND tag_value='true'
                       and routing_id in (select routing_id  
                                          from ec.production_autoroutingtag 
                                          where tag_type = 'depaneling' 
                                            AND tag_value='false'
                                         )
                    )

它工作正常,但是当行数更多时该怎么办,请给我最好的解决方案。

提前致谢。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-25 09:23:55 3448 0
1 条回答
写回答
取消 提交回答
  • 好像

    SELECT routing_id
    FROM ec.production_autoroutingtag
    WHERE (tag_type, tag_value) IN (('mounting_type', 'smd'),
                                    ('x_ray', 'true'),
                                    ('depaneling', 'false'))
    GROUP BY routing_id
    HAVING COUNT(DISTINCT tag_type, tag_value) = 3
    
    • 更新

    如果您需要使用非等值条件来检查值,那么必须结合使用OR将条件分别检查每对(标记,值):

    SELECT routing_id,
           COUNT( tag_type) 
    FROM ec.production_autoroutingtag 
    WHERE (tag_type, tag_value) IN (('mounting_type','qfn'), ('panel_qty','1')) 
       OR (tag_type = 'bom' and tag_value >= '10')
       OR (tag_type = 'cpl' and tag_value >= '158')
    GROUP BY routing_id 
    HAVING COUNT(tag_type) = 4; 
    

    注意-比较“大于或等于”将按STRINGS进行(即“ 5”将为TRUE)!如果需要比较为数字,则必须对字段值使用正确的类型转换,对引用值使用正确的数据类型:

    SELECT routing_id,
           COUNT( tag_type) 
    FROM ec.production_autoroutingtag 
    WHERE (tag_type, tag_value) IN (('mounting_type','qfn'), ('panel_qty','1')) 
       OR (tag_type = 'bom' and tag_value + 0 >= 10)
       OR (tag_type = 'cpl' and tag_value + 0 >= 158)
    GROUP BY routing_id 
    HAVING COUNT(tag_type) = 4; 
    

    回答来源:stackoverflow

    2020-03-25 09:24:02
    赞同 展开评论 打赏
问答分类:
SQL
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载