views:

32

answers:

2

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 parameter count in the call to native function 'ISNULL'

insert into wishlists (memberid, gameid, rank)
select 
memberid, 
gameid, 
MAX(ISNULL(Rank,0))+1
from wishlists;
+1  A: 

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".

zevra0
I'm getting an " Incorrect parameter count in the call to native function 'ISNULL'" for some reason..
Mel
+2  A: 
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.

Quassnoi
Perfect, thanks! Except for AND gameid = @gameid - since that will rank only when a game appears twice in a member's list... why would you use coalesce(max) and not max(isnull) here?
Mel
@Mel: I'm more used to `COALESCE`; besides, it's a standard.
Quassnoi