2015-10-17 70 views
1

我有这个疑问这retrives从MySQL 10($限制)查询,单SQL检索来自不同表的不同的信息

"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行。 我怎样才能访问单个查询中的两个信息?它可行吗?

回答

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 
+0

这工作得更好,然后我预计,感谢您的时间来回答。 – Sutekh

0

至于其他上述提到的人是什么names.id?然而,或许下面可能是使用的假设加入应该已经从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}"; 
+0

感谢您的宝贵时间。 – Sutekh