从连接表中获取额外数据

时间:2010-08-30 23:33:38

标签: sql mysql

好的,我有这个结构

产品

* PRODUCT_ID (primary key)
* PRODUCT_NAME

分类

* CATEGORY_ID (primary key)
* CATEGORY_NAME
* CODE

PRODUCT_CATEGORIES_MAP

* PRODUCT_ID (primary key, foreign key to PRODUCTS)
* CATEGORY_ID (primary key, foreign key to CATEGORIES)
* QUANTITY

我正在使用此查询

SELECT * FROM `products`
where id in (
    SELECT `product_id`
    FROM `categorizations`
    WHERE category_id = (
        SELECT id
        FROM `categories`
        where code = 'something'))

这很有效,但我只是得到了产品清单。我需要连接表中每一个的数量

5 个答案:

答案 0 :(得分:3)

说明中的表名与示例查询不同。我使用了你查询中的那些。

SELECT p.product_id  ,
       p.product_name,
       pc.quantity
FROM   `products` p
       JOIN `categorizations` pc
       ON     p.id = pc.`product_id`
       JOIN `categories` c
       ON     c.id = pc.category_id
WHERE  c.code      = 'something'

答案 1 :(得分:2)

sql有点生疏,但这里有了

选择PRODUCT_ID,PRODUCT_NAME,QUANTITY
产品分类为A,PRODUCTS_CATEGORIES_MAP为B,分类为C
其中A.PRODUCT_ID = B.PRODUCT_ID
和C.CATEGORY_ID = B.CATEGORY_ID
和C.CODE ='某事'

答案 2 :(得分:1)

如果产品属于更多类别,您可能需要总结数量。

select p.*, 
       sum(m.quantity) quantity
  from products p
  join categorizations m on m.product_id = p.product_id
  join categories on c.category_id = m.category_id 
   and c.code = 'something'
 group by p.product_id

否则请查看@Martin代码

答案 3 :(得分:0)

您想要的详细信息是产品的数量,因此,为什么不从它们开始......您可以随时检索产品,因为您拥有product_id。

SELECT * FROM (SELECT `product_id`, `quantity`
    FROM `categorizations`
    WHERE category_id = (
        SELECT id
        FROM `categories`
        where code = 'something'))) AS `filtered_categorization`
LEFT JOIN `products`
    ON (`products`.`id` == `filtered_categorization`.`product`);

答案 4 :(得分:0)

试试这个......

select
 p.*,
 c.category_id,
 c.category_name,
 pcm.quantity
from
 products p
inner join product_categories_map pcm on p.product_id = pcm.product_id
inner join categories c on pcm.category_id = c.category_id
where
 c.code = 'something'
order by
 p.product_id, c.category_id;