mysql - SQL | insert into + select + variables with condition? -
my task inserting 3 random datas per id table
, got mistake syntax
set @num := 0, @type := '' ,@stat :=''; insert random ( select * ( select userid,username, chaid, chaname,goal,gender, @num := if(@type = userid, @num +1,1) row_number, @type := userid dummy, @stat status userchar order userid ) x x.row_number <= 3)
i'm going put code in event scheduler insert new datas in daily
1064 - have error in sql syntax; check manual corresponds mariadb server version right syntax use near 'insert random ( select * ( select userid,username, chaid, c' @ line 2
thank every suggestions.
i suspect problem trying run multiple statements @ same time. can fix initializing variables in query itself:
insert random( . . . ) select u.* (select userid, username, chaid, chaname, goal, gender, (@num := if(@u = userid, @num +1, if(@u := userid, 1, 1) ) ) row_number, userid dummy, @stat status userchar u cross join (select @u = '', @num := 0, @stat := '') params order userid, rand() ) u u.row_number <= 3;
there several other issues:
- when using
insert
, list columns. particularly important if learning sql, learn habits. - you should not assign variable value in 1 expression , use in another. mysql (and mariadb) not guarantee order of evaluation of expressions in
select
, expressions can evaluated in either order. - if want random rows, use
rand()
. there difference between "indeterminate" , "random".
Comments
Post a Comment