gpt4 book ai didi

mysql - 获取一些行作为列

转载 作者:行者123 更新时间:2023-11-29 12:06:15 24 4
gpt4 key购买 nike

我有 2 张 table :

table1:         |id|create_date|title  |type  |         -------------------------------          | 1|2015-07-20 |bla-bla|TICKET|table2_meta:         |id|table1_id|meta_name|meta_value|         -----------------------------------          | 1| 1       | status  | new      |         | 2| 1       | priority| low      |         | 3| 1       | owner   | alex     | 

Now, i wish to select it like this:

            |id|create_date|title  |status|priority|owner|            |1 |2015-07-20 |bla-bla|new   |low     |alex |

My solution is:

SELECT 
t1.id,
t1.event_date,
case when m.meta_name="status" then m.meta_value end as status,
case when m.meta_name="priority" then m.meta_value end as priority,
case when m.meta_name="owner" then m.meta_value end as owner
FROM table1 as t1
LEFT JOIN table2_meta as m
on m.table1_id=t1.id
WHERE t1.type='TICKET'
GROUP BY t1.id

所以,它有效。不过好像有点丑。

我的问题是:
对于此选择还有其他解决方案以及如何提高其生产力吗?

最佳答案

嘿,在您的情况下尝试一下这个表的旋转 SQLFIDDLE

set @sql = null;
select
group_concat(distinct
concat(
'max(case when meta_name = ''',
meta_name,
''' then value end) AS ',
concat(meta_name)
)
) into @sql
FROM table1 as t1
LEFT JOIN table2 as m
on m.table1_id=t1.id
WHERE t1.type='TICKET';

set @sql = concat('select t1.id,', @sql, ' FROM table1 as t1
LEFT JOIN table2 as m
on m.table1_id=t1.id
WHERE t1.type=''TICKET''
GROUP BY t1.id
');

prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;

关于mysql - 获取一些行作为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31425630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com