我想从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
)
答案 0 :(得分:0)
您正在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
个值时,后一版本就可以使用。