2009-07-22 101 views
2

我有两个表,一个叫做customer,另一个叫customer_attributes从MySQL中的键值对表中获取数据

这个想法是客户表包含核心客户数据,并且可以定制应用程序以支持附加属性,具体取决于它如何使用。

customer_attributes有以下3列:

customerID 
key1 
value1 

我可以检索完整的一行,如果指定的任何附加属性,如果不是默认为空?我正在使用以下查询,但只有在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”和“测试”

回答

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

移动2 WHERE上CA1 /钙条件到JOIN条件而应该对其进行排序

+0

非常感谢你们全部3人的回答 - 阿达获得第一名的成绩。我不知道的细微差别! – 2009-07-22 11:10:08

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

只返回原因行是因为在WHERE子句中的测试。任何没有正确key1的行都会被忽略 - 否定您的LEFT JOIN。

您可以在key1的测试,移动到您的加盟条件

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