我有一个显示画廊的 php 页面。在所有项目下,我打印了一些信息,例如好/坏票(竖起/向下)以及它的浏览量。
对于内容中插入的每一行,也会有一行插入到 content_views 表中。但是,投票表将仅包含有人投票的行(1vote = 1row)。
我想选择某个类别(利基)中的所有信息(内容。*、视图和投票,如果有的话)。我遇到的问题是,如果没有投票,我的查询(见下文)将返回一个空结果。
$result = mysql_query("
SELECT content.*, content_views.views as views, votes.good, votes.bad
FROM content, content_niches, content_views , votes
WHERE content_views.content = content.record_num
AND content.approved = 2
AND content_niches.content = content.record_num
AND votes.content = content.record_num
AND content_niches.niche = '$niche'
AND content.enabled = 1
GROUP BY content.record_num
ORDER BY $orderby DESC LIMIT $from,$max_results") or die(mysql_error());
当然,我可以执行以下操作,但由于我的内容超过 50K 行,而且投票数更多,这将非常慢。
$result = mysql_query("
SELECT content.*, content_views.views as views,
(SELECT votes.good FROM votes WHERE votes.content=content.record_num) AS good,
(SELECT votes.bad FROM votes WHERE votes.content=content.record_num) AS bad
FROM content, content_niches, content_views
WHERE content_views.content = content.record_num
AND content.approved = 2
AND content_niches.content = content.record_num
AND votes.video = content.record_num
AND content_niches.niche = '$niche'
AND content.enabled = 1
GROUP BY content.record_num
ORDER BY $orderby DESC LIMIT $from,$max_results") or die(mysql_error());
这样做的“正确”方法是什么?
Edit1:新查询太慢了,怎么办?
$result = mysql_query("
SELECT content.*,content_niches.*, content_views.views as views
FROM content
INNER JOIN
content_niches ON (content_niches.content = content.record_num AND content_niches.niche = '$chanid')
INNER JOIN
content_views ON (content_views.content = content.record_num )
LEFT OUTER JOIN votes
ON (votes.video = content.record_num)
WHERE content.approved = 2
AND content.enabled = 1
GROUP BY content.record_num
ORDER BY $orderby DESC LIMIT $from,$max_results") or die(mysql_error());