使用连接表在数据库MySQL中进行错误分组

时间:2016-01-31 13:05:41

标签: mysql sql pivot

我在MySQL中有非聚合行数据,我需要创建一个数据透视。

我运行我的查询:

$ python3 encrypt.py "$(echo -ne '-----BEGIN PUBLIC KEY-----\nMIG...')"

但是我得到了这个MySQL错误:

SELECT 
  a.id,
  a.kredit_member_no,
  CASE WHEN b.slug='fullname' THEN a.value END as fullname,
  CASE WHEN b.slug='gender' THEN a.value END as gender,
  CASE WHEN b.slug='email' THEN a.value END as email
FROM kredit_data a
LEFT JOIN master_data b ON a.master_id = b.id
WHERE b.slug = 'fullname'
  OR b.slug = 'gender'
  OR b.slug = 'email'
GROUP BY a.kredit_member_no;

我删除了SELECT list is not in GROUP BY clause and contains nonaggregated column 'vortunes_db.a.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by 我得到了这个结果: enter image description here

如何按GROUP BY对其进行分组?

1 个答案:

答案 0 :(得分:2)

即使您的数据是字符串,您仍然希望在这些CASE语句上使用聚合函数将这些行转移到列中。自you have only_full_group_by turned on起,您还需要将a.id放入GROUP BY子句中,或者您需要从最终选择列表中删除该列。我建议将查询更改为:

SELECT 
  a.kredit_member_no,
  max(CASE WHEN b.slug='fullname' THEN a.value END) as fullname,
  max(CASE WHEN b.slug='gender' THEN a.value END) as gender,
  max(CASE WHEN b.slug='email' THEN a.value END) as email
FROM kredit_data a
LEFT JOIN master_data b 
  ON a.master_id = b.id
  and b.slug IN ('fullname', 'gender', 'email')
GROUP BY a.kredit_member_no;

See SQL Fiddle with Demo

您还会注意到我已将您的WHERE条款移至了JOIN,这是因为您基本上执行的是INNER JOIN而不是LEFT JOIN,这看起来并不像喜欢你的意图。