mysql查询语法,从不同的表中获取数据

时间:2012-09-11 18:53:07

标签: php mysql database

我有这个书店网站,我正在尝试生成一些有关销售的统计数据。我有两张桌子; 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只猫,3只狗和5只青蛙。我希望将一个表中的id与另一个表中的book_id进行匹配,然后为每个qty添加所有title。我有一种感觉,这涉及到SQL JOIN,但我对语法仍然不太满意。任何帮助将非常感激。

3 个答案:

答案 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

SQL Fiddle Example

答案 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

SQL Fiddle example

答案 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的帮助。