Need help with MySql query

Need help with MySql query

am 12.08.2006 20:36:56 von Administrator

I have this query which works to insert and update the row. Problem is

I need it to check and see if a value in the row is the same as the one

being set if it is then do the update part if not then don't. I need
to check setgroup. If the one in the row matches the one of the insert
then do the update otherwise don't.

Here is my code for the insert update.


cmds.CommandText = "INSERT INTO
`subjects`,`subject`,`totalbytes`,`date`,`groups`,`num`,`max `,`setgroup`)

VALUES (last_insert_id(), ?subject, ?totalbytes, ?date, ?groups, ?num,
?max, ?setgroup) on duplicate key update totalbytes = totalbytes +
?totalbytes,num = num + 1";


cmds.Prepare();
cmds.Parameters.Add("?subject", heads.RealSubject);
cmds.Parameters.Add("?totalbytes", heads.TotalBytes);
cmds.Parameters.Add("?date", heads.Date);
cmds.Parameters.Add("?groups", heads.Groups);
cmds.Parameters.Add("?num", "1");
cmds.Parameters.Add("?max", heads.MaxMessages);
cmds.Parameters.Add("?setgroup", group);
cmds.ExecuteNonQuery();

Re: Need help with MySql query

am 13.08.2006 03:35:01 von Bill Karwin

admin@binindex.net wrote:
> I need it to check and see if a value in the row is the same as the one
> being set if it is then do the update part if not then don't. I need
> to check setgroup. If the one in the row matches the one of the insert
> then do the update otherwise don't.

If setgroup is your primary key for this table, there are a couple of
solutions in MySQL:

http://dev.mysql.com/doc/refman/5.0/en/replace.html
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.h tml

However, in both of these cases, they only check for cases of duplicated
primary key value. They do not check for existing values in a different
column.

So I think you'll have to do this as a multi-step process: use a SELECT
query to find rows where `setgroup` is a certain value, and do your
insert only if none are returned in that result set.

Not every problem can be implemented in a single SQL statement.

Regards,
Bill K.