开发者

One table, need multiple values from different rows/tuples

开发者 https://www.devze.com 2023-01-03 14:05 出处:网络
I have tables like: \'profile_values\' userID | fid| value -------+---------+------- 1| 3| joe@gmail.com 1| 45| 203-234-2345

I have tables like:

'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

And:

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

I want 开发者_运维知识库to join them and have one row with two of the values like:

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

I have solved it but it feels clumsy and I want to know if there is a better way to do it. Meaning solutions that are either more readable or faster(optimized) or simply best-practice.

Current solution: multiple tables selected, many conditional statements:

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;

Thanks for the help!


It's a typical pivot query:

  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

Add "LEFT" before the "JOIN" if you want to see users who don't have any entries in the PROFILE_VALUES table.


I didn't say this, which I should have (@OMG Ponies) but I wanted to use this within a MySQL view. And for views to be editable you're not allowed to use aggregate functions and other constraints. So what I had to do whas use the same SQL query as I had described in the initial question.

Hope this helps someone, adding tag for creating views.

0

精彩评论

暂无评论...
验证码 换一张
取 消