内部查询出错,其中内部查询独立运行时不生成错误

时间:2014-12-10 15:05:13

标签: mysql inner-query

以下是我的查询,此查询给出了以下错误Unknown column 'package_id' in 'where clause

insert into company_packages(
     package_product_id
    ,product_id
    ,company_id
    ,user_id
    ,expiry_date
    ,discount) 
values(
     (select id from package_products 
     where package_id=1 and product_id=5 and status=1 limit 1)
    ,5
    ,111
    ,116
    ,'2015-06-10'
    ,0)

但是当我运行这个内部查询时,我没有收到任何错误

select id from package_products 
where package_id=1 and product_id=5 and status=1 limit 1

2 个答案:

答案 0 :(得分:1)

这个查询改为

INSERT INTO company_packages(package_product_id,product_id,company_id,user_id,expiry_date,discount) 
SELECT id, 5, 111, 116, '2015-06-10', 0 
FROM package_products 
WHERE package_id=1 AND product_id=5 AND status=1 
LIMIT 1

答案 1 :(得分:0)

尝试此操作,这样您就不会混用INSERT...VALUESINSERT...SELECT语法:

 insert into company_packages
 (
     package_product_id
   , product_id
   , company_id
   , user_id
   , expiry_date
   , discount
 ) 

select 
     id 
   , product_id
   , 111
   , 116
   , '2015-06-10'
   , 0
from package_products 
where package_id=1 
and   product_id=5 
and   status=1 
limit 1