views:

539

answers:

2

does anybody know how to do this syntax below in mysql?

without Stored Procedure

and in single query only


SELECT CASE
 WHEN COUNT(v.value) = 0 THEN (
  INSERT INTO tbl_v (fid, uid, VALUE)
  SELECT fid, 1 AS uid, 'xxxxxx' AS VALUE FROM tbl_f
  WHERE category = 'categoryname' AND NAME = 'somevalue'
 )WHEN v.value <> 'test' THEN (
  'update syntax here' /* will be similar like insert statement above */
 )ELSE (
  v.value
 )END
FROM shared_tbl_f f
INNER JOIN tbl_v v ON f.fid = v.fid
WHERE v.uid = 1 AND f.category = 'categoryname' AND f.name = 'somevalue'

note:

there's no primary key on tbl_v the unique reference for tbl_v is only a combination from column fid and column uid.

because tbl_v is a mapping table (there's no primary key there) - fid and uid is a foreign key from another table

A: 

You can't, sorry. You have to do this in a stored procedure or in your applicationlogic.

Frank Heikens
is it? previously it's used 2 queries, but I think it's more optimal if using 1 query in one go rather than multiple query called from application logic
AnD
A: 

You can use the ON DUPLICATE KEY UPDATE clause with your insert statement.

INSERT INTO tbl_v (fid, uid, VALUE)
  SELECT fid, 1 AS uid, 'xxxxxx' AS VALUE FROM tbl_f
  WHERE category = 'categoryname' AND NAME = 'somevalue'
ON DUPLICATE KEY UPDATE
  value = ?;

To get this to work their needs to be either a primary key or unique index on a column. A duplicate value will then start the update part of the statement.

Reference: http://dev.mysql.com/doc/refman/5.5/en/insert-select.html

ar
thanks for the response, butis this method still possible, if the unique key is a combination from column fid and column uid? because tbl_v is a mapping table (there's no primary key there) - fid and uid is a foreign key from another table
AnD
It sounds like there should be a composite primary key on tbl_v of (fid, uid). You could use the following to add one. `ALTER TABLE tbl_v ADD CONSTRAINT PRIMARY KEY (fid, uid);`
ar
yep it works :D thank you!
AnD