2010-06-24 45 views
1

把我的問題簡化成一個簡單的表單很困難,所以如果標題沒有意義,我很抱歉。在不影響返回行的情況下對JOINed列進行計數?

無論如何,現在的問題是:

$query = ' 
    SELECT issues.*, comments.author AS commentauthor, favorites.userid AS favorited FROM issues 
    LEFT JOIN comments ON comments.issue = issues.id AND comments.when_posted = issues.when_updated 
    LEFT JOIN favorites ON favorites.ticketid = issues.id AND favorites.userid = \'' . $_SESSION['uid'] . '\' 
    ' . $whereclause . ' 
    ORDER BY issues.when_updated ' . $order; 

不介意一個事實,即它是PHP,因爲我不要求爲PHP幫助。

的查詢檢索一堆issues,什麼我希望做的是獲得favorites行數已經favorites.ticketid匹配issues.id。我對LEFT JOIN favorites的使用不是得到我剛剛提到的,而是爲了獲得客戶是否喜歡這個問題,因此favorites.userid AS favorited

我曾嘗試做以下幾點:(全部一次,我把這個在可讀性符號形式)

  • 複製現有LEFT JOIN favorites,並從重複
  • 刪除用戶ID檢查添加, COUNT(favorites.ticketid) AS favoritescountSELECT
  • 添加AS favorited到原始LEFT JOIN以及改變favorites.useridfavorited.userid

有了這個嘗試,我的查詢最終只返回一行。

回答

0
SELECT issues.*, 
     comments.author AS commentauthor, 
     favorites.userid AS favorited, 
     (
      SELECT COUNT(favorites.id) 
      FROM favorites 
      WHERE ticketid = issues.id 
     ) AS numfavorites 
FROM issues 
LEFT JOIN comments 
    ON comments.issue = issues.id 
    AND comments.when_posted = issues.when_updated 
LEFT JOIN favorites 
    ON favorites.ticketid = issues.id 
    AND favorites.userid = ?uid 

這應該工作,我只是使用子查詢得到的最愛

相關問題