MYSQL列分为具有列名称的行

时间:2019-11-01 21:04:14

标签: mysql sql pivot

我想将查询结果的列变成行。是的,这是一个枢轴,有关枢轴的文章很多。忍受我。这是关于基于子查询而不是表和聚合的数据透视。

我有一个查询,该查询返回单行:数据库中各种表中某个人的详细信息。该查询类似于:

SELECT *
FROM (
    SELECT wp_usermeta.meta_value AS member_id
    FROM wp_usermeta
    WHERE wp_usermeta.user_id=1234 AND
      wp_usermeta.meta_key="member_id") AS m
LEFT JOIN tabMembers ON tabMembers.ID=m.member_id

返回的截短版本(仅6列)是:

id first last   phone        level cert
-- ----- -----  ------------ ----- ----
25 john  smith  111-222-3333 5     no

我想将结果的列变成行,如:

Field  Value
-----  -----
id     25
first  john
last   smith
email  js@example.com
phone  111-222-3333
level  5
cert   no

我无法解决如何构造使用此结果来生成第二张表的查询。我知道这可能是一系列SELECT ... UNION语句。

SELECT "id" AS "Field", tabMembers.`id` AS "Value" FROM tabMembers WHERE tabMembers.ID=m.member_id UNION
SELECT "first" AS "Field", tabMembers.`first` AS "Value" FROM tabMembers WHERE tabMembers.ID=m.member_id UNION
SELECT "last" AS "Field", tabMembers.`last` AS "Value" FROM tabMembers WHERE tabMembers.ID=m.member_id UNION
SELECT "phone" AS "Field", tabMembers.`phone` AS "Value" FROM tabMembers WHERE tabMembers.ID=m.member_id UNION
SELECT "level" AS "Field", tabMembers.`level` AS "Value" FROM tabMembers WHERE tabMembers.ID=m.member_id UNION
SELECT "cert" AS "Field", tabMembers.`cert` AS "Value" FROM tabMembers WHERE tabMembers.ID=m.member_id

我要避免的是运行第一个查询,该查询在每个SELECT ... UNION语句中一遍又一遍地提取member_id。

理想情况下,这只是在结果的列名上循环,而该列名将从表模式中提取,但是同样,我在将其包裹在形式上时遇到了麻烦。

0 个答案:

没有答案