小编典典

从MySQL中的键值对表中检索数据

sql

我有两个表,一个叫customer,一个叫customer_attributes

这个想法是,客户表包含核心客户数据,并且可以根据应用程序的用途对应用程序进行自定义以支持其他属性。

customer_attributes 有以下3列:

customerID
key1
value1

我是否可以检索整行,如果指定了其他任何属性,如果没有,则默认为NULL?我正在使用以下查询,但只有两个属性都存在于customer_attributes表中时,它才有效。

SELECT `customer`.*, `ca1`.`value1` AS `wedding_date`, `ca2`.`value1` AS `test` 
FROM `customer` 
LEFT JOIN `customer_attributes` AS `ca1` ON customer.customerID = ca1.customerID 
LEFT JOIN `customer_attributes` AS `ca2` ON customer.customerID = ca2.customerID 
WHERE (customer.customerID = '58029') 
   AND (ca1.key1 = 'wedding_date') 
   AND (ca2.key1 = 'test')

在这种情况下,我感兴趣的两个属性称为“ wedding_date”和“ test”


阅读 205

收藏
2021-03-10

共1个答案

小编典典

试试这个:

SELECT `customer`.*, `ca1`.`value1` AS `wedding_date`, `ca2`.`value1` AS `test` 
FROM `customer` 
LEFT JOIN `customer_attributes` AS `ca1` ON customer.customerID = ca1.customerID  AND ca1.key1='wedding_date'
LEFT JOIN `customer_attributes` AS `ca2` ON customer.customerID = ca2.customerID AND ca2.key1='test'
WHERE (customer.customerID = '58029')

将ca1 / ca2上的2个WHERE条件移到JOIN条件中,应对其进行排序

2021-03-10