简体   繁体   English

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

[英]mysql query syntax, get data from different tables

I got this bookshop website, and I'm trying to generate some statistics about sales. 我有这个书店的网站,并且我试图生成一些有关销售的统计信息。 I've got two tables; 我有两张桌子。 books and sales_item . bookssales_item They look like this: 他们看起来像这样:

books

id  title
1   Cats
2   Dogs
3   Frogs

and sales_item sales_item

book_id  qty
1        2
2        2
3        4
3        1
2        1
and so on for hundreds of rows

So what I'm after is a sql query and a html table that tells me that we've sold 2 Cats, 3 Dogs and 5 Frogs. 因此,我需要的是一个sql查询和一个html表,该表告诉我我们已经出售了2只猫,3只狗和5只青蛙。 I want to match id from one table with book_id from the other and then add all the qty for each title . 我想将一个表中的id与另一个表中的book_id匹配,然后为每个title添加所有qty I have a feeling that this involves sql JOIN but I'm still not very comfortable with the syntax. 我感觉这涉及sql JOIN,但是我对语法仍然不太满意。 Any help would be much appreciated. 任何帮助将非常感激。

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 SQL小提琴示例

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 SQL Fiddle示例

You can do this: 你可以这样做:

$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>";

Got help from a w3school example . 从w3school的例子中得到了帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM