sql-一个表,需要来自不同行/元组的多个值

我有这样的表:

'profile_values'
userID | fid     | value  
-------+---------+-------
1      | 3       | joe@gmail.com
1      | 45      | 203-234-2345
3      | 3       | jane@gmail.com
1      | 45      | 123-456-7890

和:

'users'
userID | name       
-------+-------
1      | joe      
2      | jane     
3      | jake    

我想加入它们,并在其中包含两个值,例如:

'profile_values'
userID | name  | email          | phone
-------+-------+----------------+--------------
1      | joe   | joe@gmail.com  | 203-234-2345
2      | jane  | jane@gmail.com | 123-456-7890

我已经解决了它,但是感觉很笨拙,我想知道是否有更好的方法可以做到.更具可读性或更快速(优化)或仅是最佳实践的含义解决方案.

当前解决方案:选择了多个表,许多条件语句:

SELECT u.userID AS memberid,
       u.name AS first_name, 
       pv1.value AS fname,
       pv2.value as lname
FROM  users AS u,
      profile_values AS pv1, 
      profile_values AS pv2,
WHERE u.userID = pv1.userID
  AND pv1.fid = 3
  AND u.userID = pv2.userID
  AND pv2.fid = 45;

谢谢您的帮助!

解决方法:

这是一个典型的数据透视查询:

  SELECT u.userid,
         u.name,
         MAX(CASE WHEN pv.fid = 3 THEN pv.value ELSE NULL END) AS email,
         MAX(CASE WHEN pv.fid = 45 THEN pv.value ELSE NULL END) AS phone,
    FROM USERS u
    JOIN PROFILE_VALUES pv ON pv.userid = u.userid
GROUP BY u.userid, u.name

如果要查看PROFILE_VALUES表中没有任何条目的用户,请在“ JOIN”之前添加“ LEFT”.

上一篇:mysql-不带WHERE语句的INT比较


下一篇:Davinci DM6446开发攻略-UBOOT-2009.03移植2 nand flash的烧写