dpo15099 2017-01-18 15:07
浏览 187

使用键值对连接MySQL表

I have a table structure as described below:

persons
+----+------+
| id | name |
+----+------+
| 1  | Bart |
| 2  | Lisa |
+----+------+

keys
+----+--------+
| id | key    |
+----+--------+
| 1  | gender |
| 2  | age    |
+----+--------+

values
+----+-----------+--------+--------+
| id | person_id | key_id | value  |
+----+-----------+--------+--------+
| 1  | 1         | 1      | male   |
| 2  | 1         | 2      | 10     |
| 3  | 2         | 1      | female |
| 4  | 2         | 2      | 8      |
+----+-----------+--------+--------+

And I would need to get result a table like this:

+-----------+------+--------+-----+
| person_id | name | gender | age |
+-----------+------+--------+-----+
| 1         | Bart | male   | 10  |
| 2         | Lisa | female | 8   |
+-----------+------+--------+-----+

I can achieve this by using LEFT JOINs, but that doesn't work dynamically.

I could make a PHP script that would generate the SQL, but there must be way to make a query that works dynamically.

  • 写回答

1条回答 默认 最新

  • dp19001 2017-01-18 15:10
    关注

    Conditional Aggregation + Join

    SELECT p.person_id,
           p.NAME,
           Max(CASE WHEN key_id = 1 THEN value END) AS Gender,
           Max(CASE WHEN key_id = 2 THEN value END) AS Age
    FROM   VALUES v
           JOIN person p
             ON v.person_id = p.id
    GROUP  BY p.person_id,
              p.NAME 
    

    Get rid of Keys and Values table and add two columns called Age and Gender in Person table itself

    评论

报告相同问题?

悬赏问题

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