我一直试图了解查询的行为,但我不完全了解发生了什么。
看看:
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'
)
)
您能解释一下为什么使用子查询的原因,为什么在这种情况下LEFT JOIN很重要以及条件 entity_type_code ='catalog_product_info'?
谢谢
答案 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_varchar
中entity_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'
)
)
)
我希望这将有助于理解查询,尽管没有数据来回答“为什么使用子查询”等也是不可能的。