由于这个mysql查询,我的网站非常慢。
SELECT content.*,
(SELECT content_views.views FROM content_views WHERE content_views.content = content.record_num) as views ,
(SELECT images.filename FROM images WHERE images.record_num = content.thumbnail) AS thumbfile
FROM content WHERE enabled = 1 $filterAnd
ORDER BY RAND()
LIMIT $from,$max_results
我知道最好的方法就是这样使用它:
SELECT name
FROM random AS r1 JOIN
(SELECT CEIL(RAND() *
(SELECT MAX(id)
FROM random)) AS id)
AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1
但我使用多个mysql表我不知道如何使用我的查询这样的人可以帮助我吗?
谢谢
编辑:
我试过了:
SELECT content.*,
(SELECT content_views.views FROM content_views WHERE content_views.content = content.record_num) as views ,
(SELECT images.filename FROM images WHERE images.record_num = content.thumbnail) AS thumbfile
FROM content AS r1 JOIN
(SELECT (RAND() * (SELECT MAX(record_num) FROM content)) AS id) AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1
但现在我收到错误:未知表格'内容'
答案 0 :(得分:0)
此代码从内容表中选择一个随机行。
(SELECT
*
FROM
content AS r1
JOIN
(SELECT
CEIL(RAND() * (SELECT
MAX(id)
FROM
content WHERE enabled = 1 $filterAnd)) AS id
) AS r2
WHERE
r1.id >= r2.id AND r1.enabled=1 AND $filterAnd
ORDER BY r1.id ASC
LIMIT 1) randomTable
现在,您需要将此查询视为名为randomTable
字段的表,如content
表中所示。现在你可以从它中选择,加入它,来做你需要的一切。注意$filterAnd
- 我用了两次。仅当$filterAnd
包含与content
表相关的条件时才会有效。
答案 1 :(得分:0)
您已为表content
提供了一个名为r1
的别名。然后,您需要使用该别名来引用该特定表:
SELECT r1.*,
(SELECT cv.views
FROM content_views cv
WHERE cv.content = r1.record_num
) as views,
(SELECT i.filename
FROM images i
WHERE i.record_num = r1.thumbnail
) AS thumbfile
FROM content r1 JOIN
(SELECT RAND() * (SELECT MAX(record_num) FROM content) AS id
) r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1
此版本具有许多表的表别名。
答案 2 :(得分:0)
到目前为止,大多数建议都假定AUTO_INCREMENT
id没有漏洞。如果这不适用,请参阅my blog了解该解决方案,再加上7个。