单个SQL从不同的表

时间:2015-10-17 09:19:04

标签: mysql

我有这个查询从MySQL回收10($有限)查询,

"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"

这个查询对于已经存在于数据库中并且有投票的帖子非常有用,但新帖子不会显示。 投票行是"插入"第一次有人投票。我想这就是为什么他们不会被列为没有unique_content_id连接的原因。

如果我将查询更改为:

"SELECT content.loc,content.id,content.title
FROM 
content
ORDER BY content.id DESC $limit"

它有效,但我无法访问voting_count.up& voting_count.down行。 我如何在单个查询中访问这两个信息?它可行吗?

2 个答案:

答案 0 :(得分:0)

如果其中一个表中可能不存在某些数据,则应使用INNER JOIN而不是LEFT JOIN

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

答案 1 :(得分:0)

正如上面提到的那样,names.id是什么?但是,假设联接应该从content.idvoting_count.unique_content_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}";