0

我得到了这个书店网站,我正在尝试生成一些关于销售的统计数据。我有两张桌子;bookssales_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 Cats、3 Dogs 和 5 Frogs。我想id从一个表与另一个表匹配book_id,然后qty为每个表添加所有title。我有一种感觉,这涉及到 sql JOIN,但我仍然对语法不太满意。任何帮助将非常感激。

4

3 回答 3

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

SQL 小提琴示例

于 2012-09-11T18:56:16.783 回答
1
select sum(qty), title
from sales_item s
left join books b on s.book_id = b.id
group by s.book_id

SQL 小提琴示例

于 2012-09-11T18:58:29.643 回答
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示例中获得帮助。

于 2012-09-11T19:17:49.043 回答