开发者

insert into table where if not in list

开发者 https://www.devze.com 2022-12-29 22:10 出处:网络
Can anybody help me with the syntax? insert into history (company,partnumber,price) values (\'blah\',\'IFS0090\',\'0.00\')

Can anybody help me with the syntax?

insert into history (company,partnumber,price) 
 values ('blah','IFS0090','0.00') 
 if company NOT IN ('blah','blah2','blah3','blah4','blah4') 
 and partnumber='IFS0090';

Background:

I have a history table which stores daily company, products and prices. But sometimes a compan开发者_Go百科y will remove itself for a few days. Complicating the issue is because I'm only saving daily CHANGES to prices only and not snapshotting the entire days list (the data would be huge) when I display the data the company will still come up for the previous days price. So I need to do something like this, where a 0.00 price means they're no longer there.


Use:

INSERT INTO HISTORY
  (company, partnumber, price)
 SELECT 'blah', 'IFS0090','0.00'
   FROM HISTORY h
  WHERE h.company NOT IN ('blah','blah2','blah3','blah4','blah4') 
    AND h.partnumber = 'IFS0090'


You are mixing two completely different concepts in your statement. Choose one:

  • Either you want to INSERT constant values (in that case make your checks in your programming language and generate the INSERT INTO ... VALUES (...) accordingly)
  • or insert the filtered contents of another table.

The latter is possible in MySQL (that's the INSERT ... SELECT syntax), the query would look like this:

INSERT INTO history (...)
SELECT ...
FROM liveTable
INNER JOIN moreTables ...
--# this is a regular SELECT statement, as you might have guessed by now
WHERE company NOT IN ('blah','blah2','blah3','blah4','blah4') 
AND partnumber='IFS0090';
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号