我有两个表,为简单起见,表 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_id
和 key
上使用子选择:
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/