mysql - 在 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'
)
)
它工作正常,但是当行数更多时,请给我最好的解决方案。
提前致谢。
解决方案
好像
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;
推荐阅读
- python - 通过扩展用户模型中的电话字段登录
- python-2.7 - 无法使用 Anaconda 4.3.1(64 位)和 Python 2.7.13 连接到 Teradata
- neo4j - Neo4j:如何通过距离为每个节点查找下一个邻居并创建关系
- c++ - 为什么代码会抛出非法内存访问错误
- javascript - Angular *ngFor“id”标签生成不正确与`mat-button-toggle`
- azure-devops - 我可以将现有的 NuGet 包上传到 Azure DevOps 工件源吗?
- javascript - 如何使用 Tornado > 4.1 从 HTML5 表单上传大文件
- python - 如何使用 GPU 使用 tf.lite.Interpreter(在 python 中)运行 tflite 模型(*.tflite)?
- xquery - xquery 根据某些条件跳过 xml 记录
- html - HTML 输入表单中的更改不会影响 DOM