复杂的wordpress元sql查询

时间:2015-06-10 12:35:21

标签: mysql sql wordpress

表结构(例如)

id(pk) | post_id |    meta_key     | meta_value
1            1       some_0_key_x      value1
2            1       some_0_key_y      value2
3            1       some_1_key_x      value3
4            1       some_1_key_y      value4
5            2       some_0_key_x      value5
6            2       some_0_key_y      value6
7            2       some_1_key_x      value7
8            2       some_1_key_y      value8
...

等等

我想得到以下结果

post_id | field_joiner |       x     |      y
   1       some_0_key       value1        value2
   1       some_1_key       value3        value4
   2       some_0_key       value5        value6
   2       some_1_key       value7        value8
...

等等

修改 我的查询

SELECT  post_id, 
        substring_index(meta_key,'_',1) as field_joiner,
        max( case when substring_index(meta_key,'_',-1) = 'from' then meta_value end) as date_from,
        max( case when substring_index(meta_key,'_',-1) = 'to' then meta_value end) as date_to 
            FROM $wpdb->postmeta 
            WHERE meta_key LIKE 'kidum_%'
            GROUP BY post_id,field_joiner"

我需要在date_fromdate_to添加where子句 怎么可能?

1 个答案:

答案 0 :(得分:0)

如果你有相同的模式和有限的查找集,在这种情况下是x和y,下面的生成数据透视数据的查询应该可以解决这个问题

select 
post_id, 
substring_index(meta_key,'_',3) as field_joiner,
max( case when substring_index(meta_key,'_',-1) = 'x' then meta_value end) as x,
max( case when substring_index(meta_key,'_',-1) = 'y' then meta_value end) as y 
from table_name 
group by post_id,field_joiner;