Mysql 单个SQL从不同的表中检索不同的信息
我有一个查询,它从MySQL检索10个($limited)查询Mysql 单个SQL从不同的表中检索不同的信息,mysql,Mysql,我有一个查询,它从MySQL检索10个($limited)查询 "SELECT content.loc,content.id,content.title, voting_count.up,voting_count.down FROM content,voting_count WHERE names.id = voting_count.unique_content_id ORDER BY content.id DESC $limit" 这个查询对于数据库中已经准备就绪并且有投票权的帖子来
"SELECT content.loc,content.id,content.title,
voting_count.up,voting_count.down
FROM
content,voting_count
WHERE names.id = voting_count.unique_content_id
ORDER BY content.id DESC $limit"
这个查询对于数据库中已经准备就绪并且有投票权的帖子来说非常有用,但是新帖子不会显示。
第一次有人在post上投票时,“插入”投票行。我想他们不会被列出的原因是没有唯一的内容id可以连接
如果我将查询更改为:
"SELECT content.loc,content.id,content.title
FROM
content
ORDER BY content.id DESC $limit"
它可以工作,但我无法访问voting_count.up&voting_count.down行。
如何在单个查询中访问这两个信息?是否可行?如果其中一个表中可能不存在某些数据,而不是使用
内部联接
,则应使用左联接
:
SELECT content.loc,content.id,content.title,
-- USE function COALSESCE will show 0 if there are no
-- related records in table voting_count
COALESCE(voting_count.up, 0) as votes_up,
COALSESCE(voting_count.down, 0) as voted_down
FROM content LEFT JOIN voting_count
ON content.id = voting_count.unique_content_id
ORDER BY content.id DESC
如果某个表中可能不存在某些数据,则不应使用
内部联接
,而应使用左联接
:
SELECT content.loc,content.id,content.title,
-- USE function COALSESCE will show 0 if there are no
-- related records in table voting_count
COALESCE(voting_count.up, 0) as votes_up,
COALSESCE(voting_count.down, 0) as voted_down
FROM content LEFT JOIN voting_count
ON content.id = voting_count.unique_content_id
ORDER BY content.id DESC
正如上面提到的其他人,什么是
names.id
?但是,假设联接应该是从content.id
到voting\u count.unique\u content\u id
,则以下内容可能有用:
$sql="select
c.`loc`,c.`id`, c.`title`,
case
when v.`up` is null then
0
else
v.`up`
end as 'up',
case
when v.`down` is null then
0
else
v.`down`
end as 'down'
from `content` c
left outer join `voting_count` v on v.`unique_content_id`=c.`id`
order by c.`id` desc {$limit}";
正如上面提到的其他人,什么是
names.id
?但是,假设联接应该是从content.id
到voting\u count.unique\u content\u id
,则以下内容可能有用:
$sql="select
c.`loc`,c.`id`, c.`title`,
case
when v.`up` is null then
0
else
v.`up`
end as 'up',
case
when v.`down` is null then
0
else
v.`down`
end as 'down'
from `content` c
left outer join `voting_count` v on v.`unique_content_id`=c.`id`
order by c.`id` desc {$limit}";
这比我预期的更好,谢谢你的时间回答。这比我预期的更好,谢谢你的时间回答。谢谢你的时间提问。谢谢你的时间提问。