0

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

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 */

不知道如何完成最后一部分。有任何想法吗?

4

3 回答 3

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记录不存在,语法将插入记录,如果记录已经存在,则忽略它。

于 2012-11-02T19:43:10.163 回答
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"
于 2012-11-02T19:40:21.373 回答
0

您是否尝试在每个课程 ID 和“标题 1”技能的技能 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)
    );

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

于 2012-11-02T19:53:59.790 回答