Multiple Insert statements into MySQL Case

2019-06-04 10:05发布

I'm trying to select a value (id) from a MySQL table and use it in a update statement - all in a MySQL query. The select is composed of 2 parts: if the id exists, it is returned; if not, 2 inserts are done and the id is returned.

I have the following query:

SELECT 
    (CASE a.id WHEN '' THEN (
        DELIMITER //
        INSERT INTO xxxx (item_id, date_created, date_modified) VALUES (3313, NOW(), NOW())//
        INSERT INTO yyyy (item_id, locale_id, value, date_created, date_modified) VALUES(LAST_INSERT_ID(), 2, TRIM(SUBSTRING_INDEX('some text: 250 x 46 x 584', ':', 1)), NOW(), NOW())//
        SELECT c.id FROM xxxx c JOIN yyyy d WHERE c.item_id=3313 AND d.value='some text' LIMIT 1
    ) ELSE a.id END
) AS trans_ref_id
FROM xxxx a JOIN yyyy b ON a.id = b.item_id
WHERE b.value='some text'

When i run it, i get the following error:

SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ELSE a.id END ) as trans_ref_id FROM xxxx' at line 2

Am I having the wrong approach here? Where is this error coming from?

2条回答
放我归山
2楼-- · 2019-06-04 10:32

You cannot do this with SQL. You need to use cursors. The manual has an example for you to look at. Probably best to put this in a stored procedure.

查看更多
一夜七次
3楼-- · 2019-06-04 10:38

Your creative attempt does not conform to the SELECT+INSERT syntax, which is:

INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name [(col_name,...)]
    SELECT ...
    [ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
查看更多
登录 后发表回答