我怎么能用MySQL做到这一点?

时间:2011-12-02 21:44:47

标签: mysql sql

我正在使用MySQL,并有两个数据库表,如下所示:

用户

id   username
--------------
1    Bill
2    Steve

物件

user_id   key   value
----------------------
1         A     X
1         B     Y
1         C     Z
2         A     S
2         C     T

产生以下结果需要什么查询?

username   A  B  C
-------------------
Bill       X  Y  Z
Steve      S     T

我用INNER JOIN尝试了这个,但最后有5行(每个对应的对象行一个)。

任何帮助都非常感激。

3 个答案:

答案 0 :(得分:3)

如果事先知道'A''B''C',您可以这样做:

SELECT users.username,
       ( SELECT objects.value
           FROM objects
          WHERE objects.user_id = users.id
            AND objects.`key` = 'A'
       ) AS a,
       ( SELECT objects.value
           FROM objects
          WHERE objects.user_id = users.id
            AND objects.`key` = 'B'
       ) AS b,
       ( SELECT objects.value
           FROM objects
          WHERE objects.user_id = users.id
            AND objects.`key` = 'C'
       ) AS c
  FROM users
 ORDER
    BY users.username
;

答案 1 :(得分:2)

select u.username
     , oA.value A
     , oB.value B
     , oC.value C
  from users u
left
  join objects oA
    on u.id = oA.user_id
   and oA.key = 'A'
left
  join objects oB
    on u.id = oB.user_id
   and oB.key = 'B'
left
  join objects oC
    on u.id = oC.user_id
   and oC.key = 'C'

答案 2 :(得分:0)

也许这不是你要求的查询,但这是我在你的情况下使用的干净和sipmle查询:

select objects.*, matrix.*
from 
        (select users.id, o.key
          from users, (select distinct key from objects) as o
        ) 
as matrix left join objects on matrix.id = objects.user_id
                           and matrix.key = objets.key
order by matrix.id, matrix.key

此查询“填充”空白区域。因此,您可以使用两个嵌套的foreach(或类似的东西)来使用结果集,并绘制所需的表。