【问题标题】:SELECT different values on same Column在同一列上选择不同的值
【发布时间】:2016-01-21 12:15:29
【问题描述】:

我正在尝试获取一个 HTML 表格:

User's first name | User's last name | Phone | Product he bought

我有下一张桌子(使用 Woocommerce 自动制作):

meta_id  |  post_id  |  meta_key  |  meta_value

   100         41        email      email@example
   101         41        phone       666666666
   102         41       firstname       Name
   103         41       lastname       Lastname

我如何通过一个查询来选择值电子邮件、电话、名字和姓氏,以便在我的 PHP 文件中“回显”它。 尝试使用 UNION,在第一个 SELECT 中使用 SELECT ......它们没有输出我想要的。

谢谢!!

【问题讨论】:

    标签: mysql sql select


    【解决方案1】:

    一种方法是使用条件聚合:

    select post_id,
           max(case when meta_key = 'firstname' then meta_value end) as firstname,
           max(case when meta_key = 'lastname' then meta_value end) as lastname,
           max(case when meta_key = 'phone' then meta_value end) as phone,
           max(case when meta_key = 'email' then meta_value end) as email
    from t
    group by post_id;
    

    条件聚合使得添加新列或在重复键时将值连接在一起变得非常容易(提示:使用group_concat())。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多