开发者

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

开发者 https://www.devze.com 2023-03-14 20:28 出处:网络
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 opp

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!


You can most likely achieve what you want using a pivot table: http://en.wikibooks.org/wiki/MySQL/Pivot_table

0

精彩评论

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