1

我目前通过使用 SELECT 而不是 VALUES 的方式插入数据,因为它是默认的。问题是,只有当数据不在数据库中时,我才能找到插入数据的方法。

这是我当前的查询:

INSERT INTO collectives_users(id_user,id_artistname,id_collective,users_type,status)
SELECT
    (SELECT id_user FROM artistnames WHERE artistname = 'yoannis'),
    (SELECT id FROM artistnames WHERE artistname = 'yoannis'),
    ('1'),(2),(0)
UNION ALL
SELECT
    (SELECT id_user FROM artistnames WHERE artistname = 'paul'),
    (SELECT id FROM artistnames WHERE artistname = 'paul'),
    ('1'),(4),(0)

我试过了

INSERT IGNORE INTO

不起作用并且不是很合适(不返回错误)

我也试过

AND NOT EXIST

不工作。

如果您有想法,请不要犹豫。

4

2 回答 2

2

你试过REPLACE语法吗?它的工作原理与 INSERT 相同,只是使用REPLACE而不是INSERT.

在collectives_users 表中设置一个虚拟列怎么样,这样我们就可以计算找到重复项的次数。这样,我们可以使用以下INSERT ... ON DUPLICATE KEY UPDATE语法:

INSERT INTO collectives_users(id_user,id_artistname,id_collective,users_type,status)
SELECT
    (SELECT id_user FROM artistnames WHERE artistname = 'yoannis'),
    (SELECT id FROM artistnames WHERE artistname = 'yoannis'),
    ('1'),(2),(0)
UNION ALL
SELECT
    (SELECT id_user FROM artistnames WHERE artistname = 'paul'),
    (SELECT id FROM artistnames WHERE artistname = 'paul'),
    ('1'),(4),(0)
ON DUPLICATE KEY UPDATE dummy_column = dummy_column + 1;

另一种方法是创建一个存储过程。这更棘手。

示例代码:

DELIMITER \\
DROP PROCEDURE IF EXISTS sp_test\\
CREATE PROCEDURE sp_test(in_id_user, in_id_artistname, in_id_collective, in_users_type, in_status)
BEGIN

CASE
    WHEN NOT EXISTS (SELECT id_user FROM artistnames WHERE artistname = 'yoannis')  OR ...
    THEN INSERT ...
END CASE;

END\\
DELIMITER ;

MySQL Reference Manual for INSERT ... ON DUPLICATE KEY UPDATECASE语法1中的更多信息。

于 2013-05-04T15:50:41.613 回答
0

正如您拥有的那样,UNIQUE您可以ON DUPLICATE KEY UPDATE毫无风险地使用,并且重复值将被更新,以便没有重复,就像虚拟列的想法一样:

INSERT INTO collectives_users(id_user,id_artistname,id_collective,users_type,status)
SELECT
    (SELECT id_user FROM artistnames WHERE artistname = 'yoannis'),
    (SELECT id FROM artistnames WHERE artistname = 'yoannis'),
    ('1'),(2),(0)
UNION ALL
SELECT
    (SELECT id_user FROM artistnames WHERE artistname = 'paul'),
    (SELECT id FROM artistnames WHERE artistname = 'paul'),
    ('1'),(4),(0)
ON DUPLICATE KEY UPDATE dummy_column = dummy_column + 1;

我建议你WHERE NOT EXISTS改用

INSERT INTO collectives_users(id_user,id_artistname,id_collective,users_type,status)
SELECT
    (SELECT id_user FROM artistnames WHERE artistname = 'yoannis'),
    (SELECT id FROM artistnames WHERE artistname = 'yoannis'),
    ('1'),(2),(0)
UNION ALL
SELECT
    (SELECT id_user FROM artistnames WHERE artistname = 'paul'),
    (SELECT id FROM artistnames WHERE artistname = 'paul'),
    ('1'),(4),(0)
WHERE NOT EXISTS(SELECT Id 
       FROM collectives_users t2
       WHERE t2.Id = artistnames.Id

我没有尝试代码,但它是您可以查看的地方。此外,有关此线程中“不存在”的更多信息。

于 2013-05-04T17:24:01.753 回答