使用select语句将Srt插入到语句中

cha*_*ura 8 sql insert

我想从表(item2)中的表(item1)和不在该item2表中的日期插入一些值.

如何使用select语句将SQL插入语句写入语句来实现?

例如:

INSERT into item1(date, name, qty) 
values(datevalue, select col1, col2 from item2);
Run Code Online (Sandbox Code Playgroud)

这不起作用.我该怎么做才能解决这个问题?

insert into daily_stock(date, product_id, name, weight, qty, free_issues, sales_price, 
                        purchased_price, category, last_purchased_date) 

     select 
        **'"+today+"'**,
        productId, name, weight, newQty, freeIssues, NewSalesPrice,
        NewPurchasePrice, category, datePurchased 
     from product
Run Code Online (Sandbox Code Playgroud)

我正在使用java,今天是一个字符串变量,仍然没有数据插入,什么是错的?

dav*_*vek 7

你几乎就在那里:只需使用SELECT变量for INSERTinstread VALUES,并将你的数据作为常量包含在内:

insert into item1(date,name,qty) 
select <datevalue>, col1, col2 from item2;
Run Code Online (Sandbox Code Playgroud)

如果您的日期来自另一个表,您可以这样做:

 insert into item1(date,name,qty) 
 select d.dcol1, i2.col1, i2.col2 
 from item2 i2 inner join table_containing_date_col d
 on <some join criteria>
Run Code Online (Sandbox Code Playgroud)

编辑:你必须确保数据类型,即符合您必须是可解析为一个日期,如果你是savign它日期字段(你是,希望!).您没有提供数据库的详细信息,但对于SQL Server,它将是这样的

cast('your date in yyyymmdd format' as datetime) 
Run Code Online (Sandbox Code Playgroud)

(yyyymmdd总是以可识别的ISO格式工作)

或者更好的还是CONVERT

对于MySql,您有STR_TO_DATE,对于Oracle TO_DATE等等.