Help with MySQL query synatx
I want to insert a row of data into a table with five columns (this table joins members and games); four of the five columns are known, while the fourth, rank, has to be dynamically calculated:
wishlists(id (int, pk), memberid (int, FK), gameid(int, FK), rank (int), createdat(timestamp) )
INSERT INTO wishlists (memberid, gameid, rank)
VALUES (somememberid, somegameid, )
The value rank needs to search the table and find all the records belonging to a certain member, figure out the ranks, and insert the new record with the lowest rank.
rank = MAX(ISNULL(Rank,0))+1
I've tried a few variations, but I can't get the syntax right. I know how to do it in two queries, but I can't figure out how to do it in one query.
EDIT The following code, which I have used on a prior occasion, yields [Err] 1582 - Incorrect paramete开发者_高级运维r count in the call to native function 'ISNULL'
insert into wishlists (memberid, gameid, rank)
select
memberid,
gameid,
MAX(ISNULL(Rank,0))+1
from wishlists;
INSERT
INTO wishlists (memberid, gameid, rank)
SELECT @memberid, @gameid, COALESCE(MAX(rank), 0) + 1
FROM wishlists
WHERE memberid = @memberid
Substitute your actual memberid
and gameid
in place of @
-prefixed parameters.
Not fully sure that I understand your schema, but you're probably looking to insert using a SQL statement...
insert into wishlists (memberid, gameid, rank)
select
memberid,
gameid,
MAX(IFNULL(Rank,0))+1
from wishlists;
EDIT: syntax... should be "ifnull".
精彩评论