簡體   English   中英

MySQL - 連接和計算另一個表中的行

[英]MySQL - Join & Count rows from another table

我有 3 個表,例如:
parent(id, name)
children(id, data, parent_id, timestamp)
table_votes(id, user_id, child_id)

我想從children表中獲取具有特定parent_id所有行,還顯示table_votes中每個行的出現次數。

我嘗試了以下類似的方法,但似乎不起作用,我想我錯過了在table_votes沒有條目的所有children

SELECT  
    `children`.`id`,  
    `children`.`data`,  
    `children`.`parent_id`,  
    `children`.`timestamp`,  
    COUNT(`v`.`children_id`)  
FROM `children` LEFT JOIN `table_votes` `v` ON `children`.`id` = `v`.`child_id`  
WHERE `children`.`parent_id` = 20 ORDER BY `timestamp` ASC  

任何提示我做錯了什么?

先感謝您

有幾種可能的選擇,其中之一:

SELECT * ,
  (SELECT count(*)
   FROM `table_votes`
   WHERE `children`.`id` = `table_votes`.`child_id`) AS `Count`
FROM `children`
WHERE `parent_id` = 20

您也可以使用您的查詢,但必須添加GROUP BY

SELECT  
 `children`.`id`,  
 `children`.`data`,  
 `children`.`parent_id`,  
 `children`.`timestamp`,  
 COUNT(`v`.`children_id`)  
FROM `children` LEFT JOIN `table_votes` `v` ON `children`.`id` = `v`.`child_id`  
WHERE `children`.`parent_id` = 20 
GROUP BY `children`.`id`, `children`.`data`, `children`.`parent_id`, `children`.`timestamp`,
ORDER BY `timestamp` ASC

1) 帶有子選擇的解決方案:

SELECT  
    children.id,
    children.data,
    children.parent_id,  
    children.timestamp,  
    (select count(*) from table_votes children.id = table_votes.child_id) as cntVotes
FROM 
  children 
WHERE 
  children.parent_id = 20 
ORDER BY 
  children.timestamp ASC

2)通過分組解決方案:

SELECT  
    children.id,
    children.data,
    children.parent_id,  
    children.timestamp,  
    count(table_votes.id) as cntVotes
FROM 
  children 
LEFT JOIN
  table_votes ON children.id = v.child_id
WHERE 
  children.parent_id = 20 
GROUP BY
    children.id,
    children.data,
    children.parent_id,  
    children.timestamp
ORDER BY 
  children.timestamp ASC  

我不確定我是否正確理解了您的問題,但對我而言,您似乎想計算 table_votes 中的兒童數量而不是兒童。 嘗試以下操作:

select id, data, parent_id, timestamp, child_id
from table_votes join children on children_id.id = table_vote.child_id
where child_id = (select count(child_id) from table_vote)
and parent_id = '20'

暫無
暫無

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

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