MySQL PIVOT和JOIN内部MAX CASE

时间:2017-03-24 10:20:53

标签: mysql join max

我有两个表 domain_meta 。我想要完成的是PIVOT表domain_meta(我能够做到)并将该表与域连接。但是我无法用PIVOT和MAX CASE将这些表连接起来。是使用某种内部选择到domain_meta表的最简单方法吗?到目前为止,我的代码看起来像这样:

SELECT
*
FROM 
domain
ORDER BY id

domain_meta

SELECT
id,
domain_id,
source,
MAX(CASE WHEN (meta_key = 'domain') THEN meta_value ELSE NULL END) AS domain,
MAX(CASE WHEN (meta_key = 'ip') THEN meta_value ELSE NULL END) AS ip,
MAX(CASE WHEN (meta_key = 'link') THEN meta_value ELSE NULL END) AS link,
MAX(CASE WHEN (meta_key = 'net') THEN meta_value ELSE NULL END) AS net
FROM
domain_meta
GROUP BY id
ORDER BY id

domain domain_meta

1 个答案:

答案 0 :(得分:0)

像这样 -

SELECT
  d.id,
  d.domain,
  MAX(CASE WHEN (dm.meta_key = 'domain') THEN dm.meta_value ELSE NULL END) AS domain,
  MAX(CASE WHEN (dm.meta_key = 'ip') THEN dm.meta_value ELSE NULL END) AS ip,
  MAX(CASE WHEN (dm.meta_key = 'link') THEN dm.meta_value ELSE NULL END) AS link,
  MAX(CASE WHEN (dm.meta_key = 'net') THEN dm.meta_value ELSE NULL END) AS net
FROM
  domain d
  LEFT JOIN domain_meta dm
    ON d.id = dm.domain_id
GROUP BY d.id