简体   繁体   中英

MySQL join 1 record in table A to many in table B as a single row

I want to query across two tables: members and payments .

One member record could join with many payments. However, I need each payment record to be added as an additional column as opposed to an additional row.

Here is a simplified example:

members

member_id | first_name | last_name
5         | John       | Smith

payments

payment_id | member_id | pay_type   | amount
1          | 5         | VISA       | $20
2          | 5         | Mastercard | $40
3          | 5         | AMEX       | $10

Desired query result

member_id | first_name | last_name | payment_id1 | pay_type1 | amount_1 | payment_id2 | pay_type2  | amount_2 | payment_id3 | pay_type3 | amount_3
5         | John       | Smith     | 1           | VISA      | $20      | 2           | Mastercard | $40      | 3           | AMEX      | $10

A single row as a result, creating columns for each row in the payments table. Thanks!

您最有可能使用数据透视表来实现所需的目标: http : //en.wikibooks.org/wiki/MySQL/Pivot_table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM