我有一个显示图库的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());
答案 0 :(得分:1)
它被称为outer join
。左外连接返回左侧的所有行,仅返回右侧的所有行。
因此,举例来说,如果你的帖子有1票,帖子有0票,你就这样做了:
select *
from posts
left outer join votes
on posts.id = votes.id
它将返回所有帖子以及存在和对应的任何投票记录。
您应该学会使用ansi-join syntax而不是非ansi联接