[英]selecting values dynamic from columns using pivoting mysql
我有一个品牌表和职位表。
下面是他们的架构
品牌 :
brand_id,Friendly,short,followers,created,location,brandID,handle,url,pic,utcOffset,posts,conactions,engagedUser等(足以回答当前问题)
帖子 :
post_id,brandID,postID,句柄,已发布,内容,postType,评论等(足以回答当前问题)
其中postType =链接,状态,视频,问题,投票等
现在,我对以下查询进行了硬编码:
select b.friendly,
sum(case when p.postType='link' then 1 else 0 end) as 'link',
sum(case when p.postType='video' then 1 else 0 end) as 'video',
sum(case when p.postType='status' then 1 else 0 end) as 'status',
sum(case when p.postType='photo' then 1 else 0 end) as 'photo',
count(p.postType)
from brands b, posts p
where b.handle
in ('chevroletcanada','dodgecanada')
and p.handle=b.handle
and date(p.posted)
BETWEEN "2013-06-02" and "2013-08-11"
group by b.friendly
但是在上面的查询中,我静态地使用了postType的类型,即用于链接,状态,视频,照片。 现在,如果将新的postType添加到posts表中,则该方法将不起作用,因为我也必须更改查询。 同样,如果postType中的现有值被删除,那么查询也必须再次更改。
我的问题是如何动态实现这一点,以便在帖子表中添加新的postType值(例如tweet)时,tweet也将显示在结果集中。 与删除任何postType相同。
如果您不明白问题,请通知我。
我已阅读以下帖子,但无法弄清楚:
提前致谢!!
这是上述问题的解决方案。 动态枢纽可以这样实现:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(case when postType = ''',
postType,
''' then 1 end) as `',
postType, '`')
) INTO @sql
FROM posts;
SET @sql = CONCAT('SELECT b.friendly, count(p.postType), ', @sql, ' from brands b, posts p where b.handle in ("dodgecanada","chevroletcanada") and p.handle=b.handle
and date(p.posted) BETWEEN "2004-08-11" and "2013-09-11" group by b.friendly');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
上面的查询在SQL接口HeidiSQL中显示正确的结果。 但 在phpMyAdmin中 返回: “ #1243-给EXECUTE的未知预准备语句处理程序(stmt)”消息 。
谁能告诉我为什么呢? Mysql不支持“ prepared”语句吗? 还是运行准备好的语句的phpMyAdmin中有任何问题。 如何在phpMyAdmin中克服这个问题?有人可以告诉我如何在PHP中做到这一点吗? 谢谢!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.