简体   繁体   中英

how t use 'IF' in 'SELECT' statement with insert on mysql

my table is

id_stuff | kd_insert | name_stuff | date_createdd 
1        | 1         | example    | 2018-01-01

i create the query in mysql like this

SELECT IF ((DATE_FORMAT(NOW(),'%Y-%m') > DATE_FORMAT(MAX(date_createdd),'%Y-%m')), 
(
  INSERT INTO tabless (name_stuff) VALUES ('stuff')
), 
(
 null
)
 ) FROM tabless GROUP BY id_stuff ORDER BY kd_insert

after i run, why i get some error like this

Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTO tabless (name_stuff) VALUES ('stuff').

and how to create the right select with condition then insert ? thanks

I don't think it is possible to write insert statement like that. You can do this -

SELECT
  if(
    (DATE_FORMAT(NOW(), '%Y-%m')) > DATE_FORMAT(MAX(date_createdd), '%Y-%m'),
    (@value = 'stuff'),
    null
  )
FROM
  tabless
GROUP BY
  id_stuff
ORDER BY
  kd_insert;
INSERT INTO tabless (name_stuff) VALUES ('stuff');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM