试图理解查询(LEFT JOIN和子查询)

时间:2019-01-27 22:46:50

标签: sql

我一直试图了解查询的行为,但我不完全了解发生了什么。

看看:

SELECT main.entity_id,main.sku,name.value AS name
FROM product_entity AS main 
LEFT JOIN product_entity_varchar AS name ON main.entity_id = name.entity_id
WHERE name.attribute_id = (
    SELECT attribute_id 
    FROM ger_attribute 
    WHERE attribute_code LIKE "name"
    AND 'entity_type_id' = (
        SELECT entity_type_id
        FROM ger_entity_type
        WHERE entity_type_code = 'catalog_product_info'
    )
)

Image

您能解释一下为什么使用子查询的原因,为什么在这种情况下LEFT JOIN很重要以及条件 entity_type_code ='catalog_product_info'

谢谢

2 个答案:

答案 0 :(得分:1)

SELECT main.entity_id,main.sku,name.value AS name
FROM product_entity AS main 
LEFT JOIN product_entity_varchar AS name ON main.entity_id = name.entity_id
...

查询从拉出表product_entity开始。 LEFT JOIN允许查询访问表product_entity_varcharentity_id等于product_entity中具有相同名称的列的值的记录。

在结果集中,显示表value中列product_entity_varchar的值,别名为name

关键字LEFT使关系成为可选;如果product_entity_varchar中没有匹配的记录,则该名称将在输出中仅显示为NULL。如果它是[INNER] JOIN,则该关系将是强制性的:不匹配的记录将被过滤掉,并且不会出现在输出中。

答案 1 :(得分:1)

好。让我们澄清一下SQL中的LEFT OUTER JOIN

LEFT JOIN查询可以理解为UNION ALL版和INNER JOIN版的NOT EXIST的语法缩写。

让我们分解LEFT JOIN版的查询:

SELECT main.entity_id,main.sku,name.value AS name
FROM 
    product_entity AS main 
    LEFT JOIN product_entity_varchar AS name ON main.entity_id = name.entity_id
WHERE 
    name.attribute_id = (
        SELECT attribute_id 
        FROM ger_attribute 
        WHERE attribute_code LIKE "name"
        AND 'entity_type_id' = (
            SELECT entity_type_id
            FROM ger_entity_type
            WHERE entity_type_code = 'catalog_product_info'
        )
)

等效于:

SELECT main.entity_id,main.sku,name.value AS name
FROM 
    product_entity AS main 
    JOIN product_entity_varchar AS name 
        ON main.entity_id = name.entity_id
WHERE 
    name.attribute_id = (
        SELECT attribute_id 
        FROM ger_attribute 
        WHERE attribute_code LIKE "name"
        AND 'entity_type_id' = (
            SELECT entity_type_id
            FROM ger_entity_type
            WHERE entity_type_code = 'catalog_product_info'
        )
    )
UNION ALL
SELECT main.entity_id,main.sku, NULL AS name -- <-- Attention!
FROM 
    product_entity AS main 
    NOT EXISTS(
        SELECT * FROM  product_entity_varchar AS name 
        WHERE 
            main.entity_id = name.entity_id
            AND name.attribute_id = (
                SELECT attribute_id 
                FROM ger_attribute 
                WHERE attribute_code LIKE "name"
                AND 'entity_type_id' = (
                    SELECT entity_type_id
                    FROM ger_entity_type
                    WHERE entity_type_code = 'catalog_product_info'
                )
        )
    )

我希望这将有助于理解查询,尽管没有数据来回答“为什么使用子查询”等也是不可能的。