简体   繁体   中英

Combine key and value columns and one row in MYSQL

I want to combine multiple values just by doing a select. I have this:

| id | student_id | key       | value     |
| 1  | 1          | dad_name  | Leonel    |
| 2  | 1          | mom_name  | Mireya    |
| 3  | 1          | school    | Agape     |

And to convert it to this:

| id | student_id | dad_name | mom_name | school |
| 1  | 1          | Leonel   | Mireya   | Agape  |

One way (though admittedly not the best way) would be:

SELECT r.id, r.student_id, r.value as dad_name, r2.value as mom_name, r3.value as school 
FROM table r 
     JOIN table r2 ON r.student_id=r2.student_id 
     JOIN table r3 ON r.student_id=r3.student.id 
WHERE r.key='dad_name' 
      AND r2.key='mom_name' 
      AND r3.key='school'

You can just join the table with itself. Let's $table is the name of your table; then the query will look somethin like this

"
SELECT t1.student_id, t2.value AS dad_name, 
  t3.value AS mom_name, t4.value AS school 
FROM $table AS t1 LEFT JOIN ($table AS t2, $table AS t3, $table AS t4)
ON (t2.student_id = t1.student_id AND t3.student_id = t1.student_id 
  AND t4.student_id = t1.student_id)
"

This isn't strictly what you asked for, but as per tadman's comment, it would possibly be cleaner to do this kind of transformation on the application layer.

For example...

$output = [];
foreach($resultset as $row) {
    $output[$row->student_id]->{$row->key} = $row->val;
}

This would result in an output like this

Array
(
    [1] => stdClass Object
        (
            [dad_name] => Leonel
            [mom_name] => Mireya
            [school_name] => Agape
        )

)

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