1

我想从 MySql 表(问题)中提取 10 条随机记录并将它们插入到另一个表(活动)中,但只有不在第二个表中的记录(活动)。如果第二个表不为空,我的代码可以工作,但如果表为空,则根本不会给出任何结果。任何人都可以看到为什么以及我能做什么吗?

INSERT INTO active (quesindex)
(
SELECT DISTINCT(questions.quesindex)
FROM questions,  (
        SELECT questions.quesindex AS sid
        FROM questions, active
where  questions.quesindex NOT IN (SELECT active.quesindex FROM active )  
        ORDER BY RAND( )
        LIMIT 10
    ) tmp
WHERE questions.quesindex = tmp.sid
)
4

1 回答 1

0

您正在questionsactive表之间进行不必要的交叉连接。这个查询应该做你想做的事:

INSERT INTO active (quesindex)
    SELECT q.quesindex AS sid
    FROM questions q
    where  q.quesindex NOT IN (SELECT a.quesindex FROM active a)  
    ORDER BY RAND( )
    LIMIT 10;

这是一个替代版本,使用left outer join

INSERT INTO active (quesindex)
    SELECT q.quesindex AS sid
    FROM questions q left outer join
         active a
         on q.quesindex = a.quesindex
    WHERE a.quesindex is null
    ORDER BY RAND( )
    LIMIT 10;

例如,NULLacive.quesindex.

于 2013-09-05T20:54:03.873 回答