如果记录尚不存在,MySQL INSERT SELECT FROM多个表

时间:2012-11-02 19:38:01

标签: mysql

我正在尝试运行一个基本上如下所示的查询:

INSERT INTO lessons_skills_xref (lessons_id, skills_id)
SELECT id FROM lessons, (SELECT id FROM skills WHERE title = "title 1")
/* PSEUDO CODE - Where the ids for both lesson and skill don't already exist */

不确定如何完成最后一部分。有什么想法吗?

3 个答案:

答案 0 :(得分:4)

假设lessons_skills_xref在(lessons_id,skills_id)上有唯一键,一种简单的方法就是使用INSERT IGNORE

INSERT IGNORE INTO lessons_skills_xref (lessons_id, skills_id)
SELECT id, (SELECT id FROM skills WHERE title = "title 1") FROM lessons

如果记录尚不存在,INSERT IGNORE语法将插入记录,如果记录已经存在,则忽略它。

答案 1 :(得分:0)

INSERT INTO lessons_skills_xref (lessons_id, skills_id)

SELECT lessons.id, skills.id FROM lessons
inner join skills on <join criteria here>

where not exists (select 1 from lessons_skill_xref x where
                  x.lessons_id = lessons.id and x.skills_id = skills.id)

and skills.title = "title 1"

答案 2 :(得分:0)

您是否尝试在每个lesson.id和“title 1”技能的skills.id之间生成笛卡尔联接?我不确定你的SELECT子句是否有效。这可能是:

    INSERT INTO lessons_skills_xref (lessons_id, skills_id)
    (SELECT l.id, s.id FROM lessons l, skills s 
        WHERE s.title = "title 1"
        AND NOT EXISTS 
            (SELECT * FROM lessons_skills_xref 
                WHERE lessons_id=l.id 
                AND skills_id=s.id)
    );

请注意,这是未经测试的。