INNER or LEFT Joining Multiple Table Records Into A Single Row

前端 未结 3 1910
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 10:10

Phone Table

+----------------+-------------+
| Field          | Type        |
+----------------+-------------+
| f_id           | int(15)     |
|         


        
相关标签:
3条回答
  • 2020-12-20 10:28

    Are there limits on how many Work or Home numbers a particular Client record can have? If it can be many, then no, there is no way to make a single row. If there can be at most 1 of each, then you can just join on the phone numbers table twice.

    0 讨论(0)
  • 2020-12-20 10:31

    Though you can join several numbers (in any) into a single field:

    SELECT
      CONCAT(f_first_name, ' ', f_last_name) as Client_Name,
      GROUP_CONCAT(IF(phone_type='work',f_phone_number, NULL)) as Work_Numbers,
      GROUP_CONCAT(IF(phone_type='home',f_phone_number, NULL)) as Home_Numbers
    FROM clients
    JOIN phone
      USING (f_id)
    WHERE phone_type IN ('home', 'work')
    GROUP BY f_id;
    
    0 讨论(0)
  • 2020-12-20 10:32
    SELECT CONCAT(c.f_first_name, ' ', c.f_last_name) as Client_Name, 
           wp.f_phone_number as Work_Number,
           hp.f_phone_number as Home_Number
    
      FROM clients c
           LEFT OUTER JOIN phone hp
           ON hp.f_client_id = c.f_id
        AND
           hp.phone_type = 'home'
           LEFT OUTER JOIN phone wp
           ON wp.f_client_id = c.f_id
        AND
           wp.phone_type = 'work'
    

    With LEFT OUTER JOINs you will still get rows for clients with missing numbers. If you don't want to see those, change to INNER JOINs.

    Edit: As Nick kindly reminds me, this will return multiple rows for clients with multiple phone numbers. Once you have the data you need, you're then faced with presentation issue. You can handle that in the application layer, or make a sacrifice to the SQL gods and look into MySQL's GROUP_CONCAT() function.

    0 讨论(0)
提交回复
热议问题