2

我有两张桌子,一张叫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”

4

3 回答 3

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 条件中应该对其进行排序

于 2009-07-22T10:31:43.603 回答
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') 
于 2009-07-22T10:31:21.530 回答
1

使用 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') 
于 2009-07-22T10:31:10.703 回答