我有两个表:“系列”和“产品”
“系列”包含系列书籍的名称,“产品”包含各个书名的详细信息。
这样的事情:
Series Table:
id series_name series_description
1 Lord of the Rings Trilogy of fantasy books recently made into film
2 A Song of Ice and Fire Epic series of novels currently showing on HBO
3 Harry Potter Famous Children's book series also loved by adults
Product Table:
id product_name series_id author etc...
1 Fellowship of the Ring 1 JRR Tolkien
2 The Two Towers 1 JRR Tolkien
3 Return of the King 1 JRR Tolkien
4 A Game of Thrones 2 George R R Martin
5 A Clash of Kings 2 George R R Martin
6 A Storm of Swords 2 George R R Martin
7 A Feast for Crows 2 George R R Martin
8 A Dance with Dragons 2 George R R Martin
9 Harry Potter and the... 3 JK Rowling
etc.
我想SELECT * FROM系列和COUNT(*)FROM产品,以便查询返回一个包含系列信息的表,数据库中与每个系列对应的产品数作为表的最后一列追加。我也想通过类型来做这个,所以在那里有一个额外的WHERE子句。如果选择“Fantasy and Magic”作为类型,它会看起来像这样:
id series_name series_description number_of_products
1 Lord of the Rings Trilogy of Fantasy... 3
2 A Song of Ice and Fire Epic Series of Novels... 5
3 Harry Potter Famous Children's book... 7
我想我可能需要一个LEFT JOIN,但到目前为止,我的最佳尝试仍然存在。
这是我到目前为止所做的,但我认为这可能是完全错误的。
SELECT series.id,
series.series_name,
series.publisher_id,
series.description,
series.image,
COUNT (product.*) as nRows
FROM series
LEFT OUTER JOIN product
ON series.id = product.series_id
WHERE series.genre = 'Fantasy and Magic'
GROUP BY ... (do I need a GROUP BY?)
任何帮助都会非常感激。提前谢谢!
答案 0 :(得分:6)
几乎就在那里。试试这个。
SELECT series.id,
series.series_name,
series.publisher_id,
series.description,
series.image,
COUNT (product.id) as nRows
FROM series
LEFT OUTER JOIN product
ON series.id = product.series_id
WHERE series.genre = 'Fantasy and Magic'
GROUP BY series.id,
series.series_name,
series.publisher_id,
series.description,
series.image
答案 1 :(得分:0)
不会this提供帮助;
select s.id,
s.series_name,
s.series_description,
(select count(*) from Products p where p.series_id = s.id) number_of_products
from Series s