简体   繁体   中英

mysql: merge multiple rows into one

I have two tables: state_current and state_snapshots . state_current contains exactly 4 rows, the current values for 4 different keys:

+-----+-------+
| key | value |
+-----+-------+
| A   |     1 |
| B   |     2 |
| C   |     3 |
| D   |     4 |
+-----+-------+

Now, I want to add a row to state_snapshots that contains the values of each key in a seperate column:

+---+---+---+---+
| A | B | C | D |
+---+---+---+---+
| 1 | 2 | 3 | 4 |
| 1 | 2 | 3 | 5 |
| 1 | 2 | 4 | 5 |
 ...
+---+---+---+---+

Of course, the keys never change in state_current , only the values. What mySQL-query will create a row with the value of A in state_current in the first column, the value of B in state_current in the second and so on?

I'm new to mySQL, so thanks in advance for any help!

The simplest answer I can think about is:

insert into state_snapshots(a,b,c,d)
   values ( (select value from state_current where key='A'),
            (select value from state_current where key='B'),
            (select value from state_current where key='C'),
            (select value from state_current where key='D')
          );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM