Mysql 从表A中选择*并计算表B中与特定字段匹配的对应行数
我有两张桌子:“系列”和“产品” “系列”包含系列书籍的名称,“产品”包含单个书籍标题的详细信息 比如说:Mysql 从表A中选择*并计算表B中与特定字段匹配的对应行数,mysql,database,select,join,Mysql,Database,Select,Join,我有两张桌子:“系列”和“产品” “系列”包含系列书籍的名称,“产品”包含单个书籍标题的详细信息 比如说: 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
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.
我想从series中选择*并从product中选择COUNT(*),以便查询返回一个包含series信息的表,其中数据库中与每个series对应的product数作为表的最后一列追加。我还想按体裁做这件事,所以在那里的某个地方有一个额外的WHERE子句。如果选择“幻想与魔法”作为类型,它看起来会像这样:
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
我想我可能需要一个左路球员,但到目前为止,我最好的尝试是静脉注射
这就是我目前所知道的,但我认为这可能是完全错误的
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?)
任何帮助都将不胜感激。提前谢谢 差不多了。试试这个
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
不会有帮助的
您几乎可以按照选择的相同属性进行分组(聚合计数除外)。这可能会非常慢,因为series表的每一行都会导致products表上的子选择。可以在子选择上执行联接,子选择将获得序列id和每个序列id的所有记录数。太棒了,谢谢。我觉得自己有点傻,差一点就到了那里,在最后一道篱笆上失败了,但我感谢你的帮助。到了最后-它的工作很好,很快:)我会投你一票,但我有2分,不能这样做,没有问题。请注意,MySQL将允许您在不指定所有GROUP BY字段的情况下离开,但这不是标准的SQL(因此最好保持指定所有字段的习惯)。GROUP BY指定在要对其值进行分组的行上具有相同值的所有字段。如果在此查询中没有GROUP BY,则返回的单行将包含所有匹配产品行的计数,而序列列将包含来自未指定行的值。
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