创建存储在元表中的报告值

时间:2015-09-18 18:52:41

标签: mysql sql

我有一个如下所示的查询:

SELECT * 
FROM wp_postmeta
WHERE post_id =422

我的结果如下:

meta_id | post_id | meta_key         | meta_value
-------------------------------------------------------------------------------------------
4989    | 422     | _shipping_company| TEST
4970    | 422     | _shipping_lname  | Doe
4971    | 422     | _shipping_fname  | John
4972    | 422     | _billing_fname   | jdoe@gmail.com

输出这些值的最有效方法是:

order_id | shipping_company | Lname         | fname        | email
-------------------------------------------------------------------------------------------
422      | TEST             | Doe           | John         | jdoe@gmail.com

2 个答案:

答案 0 :(得分:1)

您应该使用PIVOT,但在MySQL中,您可以使用GROUP BYCASE来压缩EAV,如:

<强> SQLFiddleDemo

SELECT 
   post_id AS order_id,
   MAX(CASE WHEN meta_key = '_shipping_company' THEN meta_value END ) AS shipping_company,
   MAX(CASE WHEN meta_key = '_shipping_lname' THEN meta_value END ) AS Lname,
   MAX(CASE WHEN meta_key = '_shipping_fname' THEN meta_value END ) AS fname,
   MAX(CASE WHEN meta_key = '_billing_fname' THEN meta_value END ) AS email
FROM wp_postmeta
WHERE post_id =422 
GROUP BY post_id;

修改

SELECT t.*
FROM
(
SELECT 
   post_id AS order_id,
   MAX(CASE WHEN meta_key = '_shipping_company' THEN meta_value END ) AS shipping_company,
   MAX(CASE WHEN meta_key = '_shipping_lname' THEN meta_value END ) AS Lname,
   MAX(CASE WHEN meta_key = '_shipping_fname' THEN meta_value END ) AS fname,
   MAX(CASE WHEN meta_key = '_billing_fname' THEN meta_value END ) AS email
FROM wp_postmeta
WHERE post_id =422 
GROUP BY post_id
) AS t
WHERE t.email IS NOT NULL

答案 1 :(得分:0)

这是我的回答

SELECT 
 post_id aorder_id  , GROUP_CONCAT( IF(meta_key ='_shipping_company', meta_value, NULL)) company
  , GROUP_CONCAT( IF(meta_key ='_shipping_lname', meta_value, NULL)) Lname
  , GROUP_CONCAT( IF(meta_key ='_shipping_fname', meta_value, NULL)) Fname
  , GROUP_CONCAT( IF(meta_key ='_billing_fname', meta_value, NULL)) email
FROM wp_postmeta
WHERE post_id = 422
GROUP BY post_id;

或删除所有行的where或使用(422,423)

中的WHERE post_id