Mysql子查询返回多行

时间:2015-10-15 15:01:13

标签: mysql

我有两张桌子,

  • product(产品,CATEGORY_ID)
  • product_options(option_id,PRODUCT_ID)

我想在product_options = category_id

%%中插入这些产品

任何建议都将不胜感激

这是我的查询:

select (select product_id 
from oc_product 
where oc_product.product_id = oc_product_option.product_id) as product_id,
15 as option_id, '' as value,   
0 as required 
from oc_product_option 
inner join oc_product_to_category c 
on oc_product_option.product_id = c.product_id 
where c.category_id = 98 

我提供4条记录,但我想要category_id = 98的所有产品,据我所知我有很多产品category_id = 98

2 个答案:

答案 0 :(得分:0)

您应该插入oc_product_option表,而不是加入它。这只会返回已有选项的产品,而不是该类别中的所有产品。

INSERT INTO oc_product_option (product_id, option_id, value, required)
SELECT p.product_id, 15 AS option_id, '' AS value, 0 AS required
FROM oc_product AS p
JOIN oc_product_to_category AS c ON o.product_id = c.product_id
WHERE c.category_id = 98

实际上,甚至没有任何理由加入oc_product,因为您没有使用该表中的任何内容。你可以这样做:

INSERT INTO oc_product_option (product_id, option_id, value, required)
SELECT product_id, 15 AS option_id, '' AS value, 0 AS required
FROM oc_product_to_category
WHERE category_id = 98

答案 1 :(得分:0)

我对你的要求知之甚少,但我认为这对你有帮助。

SELECT 
    a.product_id, 
    15 AS option_id, 
    '' AS VALUE, 
    0 AS required 
FROM 
    oc_product a 
JOIN    
    oc_product_option b
ON  
    (a.product_id=b.product_id)
JOIN    
    oc_product_to_category c
ON  
    (a.product_id=c.product_id)
WHERE 
    c.category_id = 98;