简体   繁体   中英

SQL Join with subquery counting number of records with the same id in a different table

Okay so I have three(3) tables that i want to join together

  • tableA is the main details and primary key is row_id autoincremented
  • tableB is the exteded details and primary/foreign key is row_id coming from tableA
  • tableC stores unordered ratings and comments for a particular row_id

I want to join all these tables so that I can see all details plus the number of instances in tableC for a row_id and the avg rating.

SELECT * 
FROM  `tableA` A
LEFT JOIN  `tableB` B 
      ON A.`row_id` = B.`row_id` 
LEFT JOIN (
     SELECT COUNT( 1 ) AS  'count', Avg(`row_rating`) AS  'avg'
     FROM  `tableC` 
     GROUP BY tableC.`row_id`
)C 
     ON C.`row_id` = A.`row_id` 

ORDER BY  C.`avg` ASC 

The result of this query combines all properly but the same count and avg is displayed in all rows.

Looks like you want to group the records by row_id in inner query. In which case, you need to SELECT row_id instead of COUNT(1) , try this:

SELECT * 
FROM  `tableA` A
LEFT JOIN  `tableB` B 
      ON A.`row_id` = B.`row_id` 
LEFT JOIN (
     SELECT row_id, Avg(`row_rating`) AS  'avg'
     FROM  `tableC` 
     GROUP BY tableC.`row_id`
)C 
     ON C.`row_id` = A.`row_id` 

ORDER BY  C.`avg` ASC 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM