用于生成用户信息的SQL查询

时间:2015-12-09 07:23:07

标签: mysql sql

好的,这就是wordpress数据库结构

userid|  key  | value
1     |name   |Roi
1     |age    |25
1     |gender |m
2     |name   |Danica
2     |age    |19
2     |gender |f

如何使用这种结果一次性查询

userid|  name | age | gender
1     |  Roi  | 25  | m
2     | Danica| 19  | f

经过几个月的练习,我已经厌倦了SQL。请帮忙

3 个答案:

答案 0 :(得分:2)

你可以使用这样的一些自联接:

select 
    T.userid,
    T.value as name,
    T1.value as age,
    T2.value as gender
from your_table as T
    left outer join your_table as T1 on T1.userid = T.userid and T1.key = 'age'
    left outer join your_table as T2 on T2.userid = T.userid and T2.key = 'gender'
where T.key = 'name'

首先选择具有每个用户ID名称的记录,然后将其加入到具有相同年龄和性别用户ID的记录中。

答案 1 :(得分:0)

替代解决方案,执行GROUP BY

select id,
       max(case when key = 'name' then value end) as name,
       max(case when key = 'age' then value end) as age,
       max(case when key = 'gender' then value end) as gender,
from tablename
group by id

答案 2 :(得分:-3)

echo "
   <tr> 
    <td> userid</td>
     <td> name </td>
     <td> age </td>
     <td> gender </td>
  </tr> 
 <tr> 
   <td> $userid</td> 
   <td> $name </td> 
   <td> $age </td> 
   <td> $gender </td> 
</tr>
";