Heim  >  Fragen und Antworten  >  Hauptteil

MySQL – Wie konvertiere ich Spalten in Zeilen?

<p><br /></p> <pre class="brush:php;toolbar:false;">ID | 1 |. a1 |. b1 | 2 |. a2 |. b2 |. <p>Wie reorganisiere ich Zeilen in IDs, Spaltenüberschriften und Werte? </p> <pre class="brush:php;toolbar:false;">1 | 1 |. b1 | 1|c1|c 2 |. a2 | 2 |. b2 | 2 |. c2 |. c</pre> <p><br /></p>
P粉533898694P粉533898694453 Tage vor541

Antworte allen(1)Ich werde antworten

  • P粉511896716

    P粉5118967162023-07-25 00:05:48

    您正在尝试对数据进行反转。MySQL没有反转函数,因此您需要使用UNION ALL查询将列转换为行:

    select id, 'a' col, a value
    from yourtable
    union all
    select id, 'b' col, b value
    from yourtable
    union all
    select id, 'c' col, c value
    from yourtable

    See SQL Fiddle with Demo.

    这也可以使用CROSS JOIN来实现:

    select t.id,
      c.col,
      case c.col
        when 'a' then a
        when 'b' then b
        when 'c' then c
      end as data
    from yourtable t
    cross join
    (
      select 'a' as col
      union all select 'b'
      union all select 'c'
    ) c

    See SQL Fiddle with Demo

    Antwort
    0
  • StornierenAntwort