我想从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
)
最佳答案
您正在questions
和active
表之间进行不必要的交叉联接。该查询应执行您想要的操作:
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;
例如,当
NULL
中有acive.quesindex
个值时,后一个版本将起作用。