首页 > 解决方案 > 在 POSTGRES 中将单个列与多个值匹配而无需自连接表

问题描述

我想选择一个 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'
                                         )
                    )

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

提前致谢。

在此处输入图像描述

标签: mysqldjangopython-3.xpostgresql

解决方案


好像

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; 

请注意 - “大于或等于”的比较将作为字符串执行(即 '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; 

推荐阅读