douzuizhuo0587 2015-11-21 03:25 采纳率: 0%
浏览 25

将表B中的多行链接到MySQL中的表A中的一行

I have two tables, for simplicity, table A and table B (Note, I don't have the authority to change the structure of these tables, so I'm asking this question to get around a bad database design).

Table A has two columns:

"id"          - is the unique identifier.
"customer_id" - is the customer's ID.

So table A holds a list of customer IDs.

Table B holds properties about customers. But it does it in a weird way (again, I didn't set this up, and I can't change it). Table B has [NUMBER] columns:

"id"          - is the unique identifier.
"customer_id" - is the customer's ID.
"key"         - is the name of the key/value pair
"value"       - is the value of the key/value pair

So table B holds key/value pairs that are linked to customers by their ID.

I could join these two tables to get something like this:

+----+-------------+------------+-------+
| id | customer_id | key        | value |
+----+-------------+------------+-------+
| 0  | 5           | first_name | Bob   |
| 1  | 5           | last_name  | Jones |
| 2  | 6           | first_name | Sally |
| 3  | 6           | last_name  | Sue   |
+----+-------------+------------+-------+

But as you can see, that can be difficult to manage because information about one customer is on two different rows. What would be ideal is something like this:

+----+-------------+------------+-----------+
| id | customer_id | first_name | last_name |
+----+-------------+------------+-----------+
| 0  | 5           | Bob        | Jones     |
| 1  | 6           | Sally      | Sue       |
+----+-------------+------------+-----------+

With all of the customer's data on one row.

Is there a way to do this in a SQL query so that I don't have to mess with the results in PHP? Or will I have to pick through the data in PHP?

  • 写回答

4条回答 默认 最新

  • dongzuozhu66776 2015-11-21 03:38
    关注

    One method is conditional aggregation:

    select (@rn := @rn + 1) as id, customer_id,
           max(case when `key` = 'first_name' then value end) as first_name,
           max(case when `key` = 'last_name' then value end) as last_name
    from b cross join
         (select @rn := 0) params
    group by customer_id;
    

    I'm not sure what table a would be used for, perhaps for filtering the customer ids.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?