为什么我在这个查询中遇到这个错误?
SELECT distinct fileID
FROM ( SELECT fileID from file order by fileID desc limit 30) as R1
UNION (SELECT fileID from visit order by counter desc limit 30 )
WHERE status = 1 order by rand() LIMIT 10
错误:
您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以便使用正确的语法 靠近'WHERE status = 1 order by rand()LIMIT 10'在第1行
我想要的是选择前30个查看次数最多的文件和前30个最新文件,然后从文件状态= 1中随机选择限制10个。
答案 0 :(得分:2)
将您的两个查询放入子查询中的UNION中的最新文件和大多数访问,然后通过RAND重新排序生成的派生表,并将结果限制为10.
注意:
你声明你想要选择最近访问过的文件..但是“柜台”的排序实际上选择访问次数最多的文件..而不是最近的文件。
SELECT DISTINCT fileID
FROM (
SELECT file.fileID
FROM file
WHERE file.status = 1
ORDER BY file.fileID DESC
LIMIT 30
UNION ALL
SELECT visit.fileID
FROM visit
JOIN file ON file.fileID = visit.fileID
WHERE file.status = 1
ORDER BY visit.counter DESC
LIMIT 30
) dt
ORDER BY RAND()
LIMIT 10
作为对OP评论的反应,我在其中一个选项中添加了JOIN,以检查与访问相关的文件是否具有status = 1。
另请注意:
要使此查询快速执行大量数据,您应在字段file.status
和visit.counter
上添加索引。如果fileID
不是这些表的键/索引,那么您也应该在此字段上添加索引。
visit.file_id
不是UNIQUE
,因此上述查询可能在第二个子查询的子结果中具有相同的file_id(重复项将被最终DISTINCT
删除但是意味着第二个LIMIT 30
不能按预期工作。可能的纠正:
SELECT DISTINCT fileID
FROM (
SELECT file.fileID
FROM file
WHERE file.status = 1
ORDER BY file.fileID DESC
LIMIT 30
UNION ALL
SELECT visit.fileID
FROM visit
JOIN file ON file.fileID = visit.fileID
WHERE file.status = 1
GROUP BY visit.fileId
ORDER BY MAX(visit.counter) DESC
LIMIT 30
) dt
ORDER BY RAND()
LIMIT 10
答案 1 :(得分:0)
您想对此查询做什么?我认为,解析错误更多。
我不知道MySQL是否接受了...... ..如果是你想做的......
SELECT distinct fileID FROM (( SELECT fileID from file order by
fileID desc limit 10) as R1 UNION (SELECT fileID from visit order by
counter desc limit 10 ) as R2) WHERE R1.status = 1 order by R1.rand() LIMIT 10
答案 2 :(得分:0)
试试这个,您需要括号来关闭选择。
SELECT DISTINCT fileid
FROM ((SELECT fileid, status
FROM FILE
ORDER BY fileid DESC
LIMIT 10)
UNION
(SELECT fileid, status
FROM visit
ORDER BY counter DESC
LIMIT 10)) AS T
WHERE status = 1
ORDER BY Rand()
LIMIT 10