我有这个书店网站,我正在尝试生成一些有关销售的统计数据。我有两张桌子; books
和sales_item
。它们看起来像这样:
books
id title
1 Cats
2 Dogs
3 Frogs
和sales_item
book_id qty
1 2
2 2
3 4
3 1
2 1
and so on for hundreds of rows
所以我所追求的是一个sql查询和一个html表,它告诉我,我们已售出2只猫,3只狗和5只青蛙。我希望将一个表中的id
与另一个表中的book_id
进行匹配,然后为每个qty
添加所有title
。我有一种感觉,这涉及到SQL JOIN,但我对语法仍然不太满意。任何帮助将非常感激。
答案 0 :(得分:2)
select b.id, b.title, sum(s.qty) as NumSold
from books b
left outer join sales_item s on b.id = s.book_id
group by b.id, b.title
order by b.title
答案 1 :(得分:1)
select sum(qty), title
from sales_item s
left join books b on s.book_id = b.id
group by s.book_id
答案 2 :(得分:0)
你可以这样做:
$query = ("select sum(qty) as 'Quantity', title from books b left join sales_item s on b.id = s.bookid' group by book_id");
$result = mysql_query($query);
//and this would be the code to print the html table
echo "<table border='1'>
<tr>
<th>Quantity</th>
<th>Pet</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Quantity'] . "</td>";
echo "<td>" . $row['tittle'] . "</td>";
echo "</tr>";
}
echo "</table>";
获得了w3school example的帮助。