使用MySQL中键值对表中的数据检索行

时间:2009-07-22 10:27:28

标签: sql mysql key-value

我有两个表,一个名为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'

3 个答案:

答案 0 :(得分:4)

试试这个:

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条件中,而不是将其排序

答案 1 :(得分:2)

仅返回行的原因是由于WHERE子句中的测试。任何没有正确key1的行都会被完全忽略 - 否定你的LEFT JOIN。

您可以将key1测试移动到JOIN条件

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') 

答案 2 :(得分:1)

“key”使用LEFT OUTER JOIN谓词测试,如下:

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')