簡體   English   中英

SQL計數並從多個表聯接

[英]SQL count and join from multiple tables

有一個產品表,其中包含所有產品詳細信息。 可以將一種產品提名到流行表中,從那里不同的人可以對其進行投票。 我只需要計算注冊用戶的票數。 目前,它正在計算特定產品的所有票數。 我該如何克服這個問題? 我在下面粘貼了我的sql代碼:

SELECT popular.name, popular.product_id, product.text, product.author, count(        vote.product_id ) AS votes
FROM popular
LEFT JOIN product ON ( product.id = popular.product_id )
LEFT JOIN vote ON ( vote.product_id = popular.product_id )
where popular.hidden = '1' and
popular.name in (select registered.name from registered 
where registered.course_id='".$course_id."' and 
registered.section = '".$section."' and 
registered.term = '".$term."')
GROUP BY popular.product_id
ORDER BY votes DESC Limit 10
SELECT pop.product_id, pd.text, count( vt.product_id ) AS votes
FROM popular pop
LEFT JOIN product pd ON(pd.product = pop.product_id)
LEFT JOIN vote vt ON(vt.product_id = pop.product_id)
WHERE 1 = 1 // or pop.product_id = yourProductId here
GROUP BY pop.product.id
ORDER BY vt.votes DESC

您缺少選票和其他表格之間的連接

Select P.ID, P.text, count(v.Product_ID) as votes
FROM Product PRO
LEFT JOIN Popular Pop
  ON PRO.ID = Pop.Product_ID
LEFT JOIN VOTE V   --<-- This is missing
  on V.Product_ID = Pro.ID
Group by P.ID, Pro.Text
order by votes Desc
SELECT popular.product_id, product.text, count( vote.product_id ) AS votes
FROM popular, product, vote
WHERE product.id = popular.product_id AND product.id = vote.product_id
GROUP BY product.id
ORDER BY votes DESC

請注意,此查詢不會返回沒有投票的產品。 如果您的數據庫中有此類記錄,則應使用voteLEFT JOIN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM