2015-10-17 66 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