MySQL:如何使用INNER JOIN对其进行转换

时间:2013-04-15 21:02:30

标签: mysql sql

是否可以使用INNER JOIN s编写此查询?

SELECT links.product_id AS entity_id, products.sku, links.`linked_product_id` AS     linked_entity_id, products2.`sku` AS linked_skus
FROM catalog_product_entity AS products,
    catalog_product_link AS links,
    catalog_product_entity AS products2
WHERE links.`product_id` = products.`entity_id`
    AND links.`linked_product_id` = products2.`entity_id`

此外,catalog_product_link有一列type_id,我希望最后只获得type_id1AND catalog_product_link.type_id = 1条件的行,但它不起作用。如何仅使用type_id=1获取记录?

我遇到问题,当我在语句中添加WHERE links.type_id=1时,结果出错了。 product_id下的所有内容都是相同的数字(相同的entity_id / product_id),sku下的所有内容都是NULL。不过,linked_product_idlinked_skus是正确的。

更多信息:

catalog_product_entity

| entity_id | sku | ... |
-------------------
|    1      | abc |     |
|    2      | qwe |     |
|    3      | yui |     |

catalog_product_link

| product_id (same as entity_id) | linked_product_id | type_id |
----------------------------------------------------------------
|               1                |         5         |    1    |
|               1                |         6         |    1    |
|               2                |         1         |    2    |
|               3                |         1         |    1    |
|               3                |         2         |    1    |
|               3                |         4         |    1    |

2 个答案:

答案 0 :(得分:1)

像...一样的东西。

SELECT
    p.sku,
    l.product_id AS entity_id, l.linked_product_id AS linked_entity_id
FROM catalog_product_entity AS p
     INNER JOIN catalog_product_link AS l
         ON p.entity_id= l.product_id
WHERE l.type_id = 1

答案 1 :(得分:0)

SELECT 
   links.product_id AS entity_id, 
   products.sku, 
   links.linked_product_id AS linked_entity_id, 
   products2.sku AS linked_skus
FROM catalog_product_link AS links
INNER JOIN 
  catalog_product_entity AS products ON products.entity_id = links.product_id
INNER JOIN 
  catalog_product_entity AS products2 ON products2.entity_id = links.linked_product_id
WHERE links.type_id = 1