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

标签 php mysql

我有两个表,为简单起见,表 A 和表 B(请注意,我无权更改这些表的结构,所以我问这个问题是为了绕过糟糕的数据库设计)。

表 A 有两列:

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

所以表 A 包含客户 ID 列表。

表 B 包含有关客户的属性。但它以一种奇怪的方式进行(同样,我没有设置它,我无法更改它)。表 B 有 [NUMBER] 列:

"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

因此表 B 包含通过 ID 链接到客户的键/值对。

我可以加入这两个表来得到这样的东西:

+----+-------------+------------+-------+
| 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   |
+----+-------------+------------+-------+

但如您所见,这可能很难管理,因为有关一位客户的信息位于不同的两行中。理想的情况是这样的:

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

所有客户的数据都在一行中。

有没有办法在 SQL 查询中执行此操作,这样我就不必弄乱 PHP 中的结果?还是我必须在 PHP 中挑选数据?

最佳答案

鉴于您无法更改表结构,一种方法是在 customer_idkey 上使用子选择:

SELECT
  tableA.id,
  tableA.customer_id,
  (
     SELECT 
        tableB.`value`
     FROM tableB 
     WHERE tableB.customer_id = tableA.customer_id 
       AND tableB.`key` = 'first_name'
  ) AS first_name,
  (
     SELECT 
        tableB.`value`
     FROM tableB 
     WHERE tableB.customer_id = tableA.customer_id 
       AND tableB.`key` = 'last_name'
   ) AS last_name
FROM tableA

注意:就性能而言,此查询可能很糟糕。但是,如果您别无选择,也许缓慢的查询会促使做出决定的人允许更改结构。

关于php - 将表B中的多行链接到MySQL中表A中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33839376/

相关文章:

Java - Mysql - 多重查询

javascript - php认证跨站文件上传

php - 合并来自不同表的两个 SELECT 查询

php - iphone 开发 - 使用 PHP 和 Mysql 在真实设备上测试应用程序

php - 使用 PHP 以 MySQL 格式打印结果

php - MySQL加入3个级联表

php - mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows 等...期望参数 1 是资源

c# - 第二次更新行时发生并发错误 C#

php - 如何从 php MySQL sql 注入(inject)易受攻击的查询到 MySQLi 不易受攻击的查询

mysql - 当 "rm/usr/local/mysql"返回权限错误时如何卸载mySQL?