如何更改SQL以避免子查询

时间:2018-09-30 11:02:14

标签: mysql sql

这是我正在工作的queryie的简化版本:

SELECT 
    r.id,
    r.nr,

    MAX(CASE WHEN (rm.meta_key = 'supplier_id') THEN (SELECT suppliers.title FROM suppliers WHERE suppliers.id = rm.meta_value) ELSE NULL END) AS supplier,
    MAX(CASE WHEN (rm.meta_key = 'client_id') THEN (SELECT clients.name FROM clients WHERE clients.id = rm.meta_value) ELSE NULL END) AS client,

FROM `registries` AS r 
INNER JOIN `registries_meta` AS rm ON `r`.`id` = `rm`.`registries_id`
GROUP BY r.id
LIMIT 100

是否可以在这里避免子查询?我需要告诉Mysql“加入registries_metas,如果meta_key是client_id,则加入JOIN clients.id = meta_value并选择clients.name”。

谢谢。

3 个答案:

答案 0 :(得分:2)

我相信您想要的逻辑仅使用join

SELECT r.id, r.nr,
       c.name as client_name, s.title as supplier
FROM registries r INNER JOIN
     registries_meta rm
     ON r.id = rm.registries_id LEFT JOIN
     clients c 
     ON rm.meta_value = c.id AND rm.meta_key = 'client_id' LEFT JOIN
     suppliers s 
     ON rm.meta_value = s.id AND rm.meta_key = 'supplier_id';

如果您可以有多个客户端/供应商,则可能希望将它们全部放在一行上。这表明聚合:

SELECT r.id, r.nr,
       GROUP_CONCAT(c.name) as client_names,
       GROUP_CONCAT(s.title) as suppliers
FROM registries r INNER JOIN
     registries_meta rm
     ON r.id = rm.registries_id LEFT JOIN
     clients c 
     ON rm.meta_value = c.id AND rm.meta_key = 'client_id' LEFT JOIN
     suppliers s 
     ON rm.meta_value = s.id AND rm.meta_key = 'supplier_id'
GROUP BY r.id, r.nr;

答案 1 :(得分:1)

不要与客户和供应商联系表

SELECT 
    r.id,
    r.nr,
    c.name AS client_name,s.title as supplier
FROM `registries` AS r 
INNER JOIN `registries_meta` AS rm ON `r`.`id` = `rm`.`registries_id`
left join clients c on rm.meta_value=c.id 
left join suppliers s on rm.meta_value=suppliers.id

答案 2 :(得分:1)

尝试左加入<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>application-identifier</key> <string>TEAM_ID.BUNDLE_IDENTIFIER</string> <key>aps-environment</key> <string>production</string> <key>beta-reports-active</key> <true/> <key>com.apple.developer.associated-domains</key> <array> <string>applinks:SOME_URL</string> </array> <key>com.apple.developer.team-identifier</key> <string>TEAM_ID</string> <key>get-task-allow</key> <false/> </dict> </plist> 表。我的直觉告诉我,我们需要在子查询中进行数据透视,以找到每个键的正确元值。然后,我们可以使用该元值(应为客户ID)离开加入clients的行列。

clients