【问题标题】:Retrieving a row, with data from key-value pair table in MySQL从 MySQL 中的键值对表中检索一行数据
【发布时间】:2009-07-22 18:35:30
【问题描述】:

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

【问题讨论】:

    标签: sql mysql key-value


    【解决方案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 条件中应该对其进行排序

    【讨论】:

    • 非常感谢你们 3 位的回答 - Ada 获得了第一名。一个我不知道的细微差别!
    【解决方案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') 
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2014-09-29
        • 1970-01-01
        • 2013-08-26
        • 1970-01-01
        • 2022-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多