Mysql查询select case when true insert
有谁知道如何在 mysql 中执行下面的语法?
没有存储过程,并且仅在单个查询中
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'
注意:
tbl_v
上没有主键 tbl_v
的唯一引用只是列 fid 和列 uid 的组合。
因为 tbl_v 是一个映射表(那里没有主键) - fid 和 uid 是来自另一个表的外键。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能,抱歉。您必须在存储过程或应用程序逻辑中执行此操作。
You can't, sorry. You have to do this in a stored procedure or in your applicationlogic.
您可以在插入语句中使用
ON DUPLICATE KEY UPDATE
子句。为了使其发挥作用,它们需要是列上的主键或唯一索引。然后,重复值将启动语句的更新部分。
参考: http://dev.mysql.com/doc/ refman/5.5/en/insert-select.html
You can use the
ON DUPLICATE KEY UPDATE
clause with your insert statement.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