MySQL,选择GROUP_CONCAT并将其拆分到不同的列中

x33g5p2x  于 2023-03-28  发布在  Mysql
关注(0)|答案(2)|浏览(124)

我是MySQL的菜鸟...很难描述我的任务,所以我会用一个例子来展示它。
我有两张table:

  1. meta_data

id  key value
1   property_1  1,2,54,2
1   property_2  23424
1   property_3  cat
1   property_4  4324
1   property_5  3231
1   property_6  45
1   property_7  423424
1   property_8  868
1   property_9  2424
1   property_10 886
1   property_11 535
1   property_12 3434
1   property_13 686
1   property_14 55
1   property_15 23424
1   property_16 54534
1   property_17 868
1   property_18 4556
1   property_19 5345
1   property_20 43535
2   property_1  54,92,22
2   property_2  43443
2   property_3  dog
2   property_4  343
2   property_5  2342
2   property_6  34
  1. users

id  email
1   sdfs@ya.ru
2   gdgd@ya.ru
3   ffdg@ya.ru
4   fgdfgdf@ya.ru
5   gfg@ya.ru
6   dffet@ya.ru
7   gfg@ya.ru
8   gfg@ya.ru
9   hjg@ya.ru

在调用存储过程之后,我想得到这个:

id  property_1  property_2  property_3  email
1   "1,2,54,2"  "23424"     "cat"       "sdfs@ya.ru"

该过程必须获得输入parameter(例如“cat”)和:
1.找到property_3等于输入parameter的行并从该行得到ID(例如“1”),
1.从meta_data表中选择我需要的字段,其中id等于从第一个点开始的id(例如property_1property_2property_3),
1.然后将它们从行旋转到列,
1.最后将user表中的email与相同的id相加。
如果找到property_3匹配,则执行所有这些操作。
我想我可以用很多SELECT/FROM来做,但对我来说似乎太复杂了。
我尝试使用CASE WHEN ___ LIKE ___ THEN ___ END,但我不能成功。在这种情况下,我在分组后得到null的单元格:

SELECT id,
       CASE WHEN meta_data.key LIKE 'property_1' THEN meta_data.value END AS property_1,
       CASE WHEN meta_data.key LIKE 'property_2' THEN meta_data.value END AS property_2,
       CASE WHEN meta_data.key LIKE 'property_3' THEN meta_data.value END AS property_3
FROM meta_data
smtd7mpg

smtd7mpg1#

我猜:

SELECT 
   id, 
   meta_data1.value AS property_1,
   meta_data2.value AS property_2,
   meta_data3.value AS property_3,
   email
FROM 
   meta_data AS meta_data1, 
   meta_data AS meta_data2, 
   meta_data AS meta_data3,
   users
WHERE
   meta_data1.id = users.id AND
   meta_data2.id = users.id AND
   meta_data3.id = users.id AND
   meta_data1.key = "property_1" AND
   meta_data2.key = "property_2" AND
   meta_data3.key = "property_3"
ctzwtxfj

ctzwtxfj2#

这是一种使用GROUP BY和聚合函数MAX()的优化方法:

SELECT m.id,
       MAX(CASE WHEN m.key_ LIKE 'property_1' THEN m.value_ END) AS property_1,
       MAX(CASE WHEN m.key_ LIKE 'property_2' THEN m.value_ END) AS property_2,
       max(CASE WHEN m.key_ LIKE 'property_3' THEN m.value_ END) AS property_3,
       MAX(u.email)
FROM meta_data m
inner join users u on u.id = m.id
group by m.id

Demo here

相关问题