Php MySQL语句连接两个表并求和相同的项目数量
我有两张桌子,客户和交易Php MySQL语句连接两个表并求和相同的项目数量,php,mysql,web-application-project,Php,Mysql,Web Application Project,我有两张桌子,客户和交易 Customer: -------------------------------------------- ID | Name | Tel -------------------------------------------- 1 | Peter | 123 4567 2 | John | 456 1234 3 | Alice | 789 4561 4 | Amy
Customer:
--------------------------------------------
ID | Name | Tel
--------------------------------------------
1 | Peter | 123 4567
2 | John | 456 1234
3 | Alice | 789 4561
4 | Amy | 741 8525
Transaction:
--------------------------------------------
CustID | Books | Pens | Ruler
--------------------------------------------
1 | 2 | 0 | 1
2 | 1 | 0 | 0
1 | 0 | 3 | 0
1 | 0 | 0 | 1
2 | 1 | 1 | 1
3 | 0 | 2 | 2
我需要以下信息
Results:
-------------------------------------------------------------------
ID | Name | Tel | Books | Pens | Ruler
-------------------------------------------------------------------
1 | Peter | 123 4567 | 2 | 3 | 2
2 | John | 456 1234 | 2 | 1 | 1
3 | Alice | 789 4561 | 0 | 2 | 2
4 | Amy | 741 8525 | 0 | 0 | 0
基本上,它将汇总同一客户的书籍、钢笔和尺子
我试过:
$sql = "select
`customer`.id,
`custmaster`.name,
`custmaster`.tel,
`transaction`.id,
`transaction`.books,
`transaction`.pens,
`transaction`.ruler,
from `customer`
left join `transaction`
on `customer`.id=`transaction`.custid
ORDER BY `customer`.id ASC";
但是没有显示(我知道我在什么地方需要sum()函数。任何人都可以帮忙吗?使用
sum
和分组方式
SELECT c.id, c.name, c.tel, SUM(t.books) as books, SUM(t.pens) AS pens, SUM(t.ruler) AS ruler
FROM customer AS c
LEFT JOIN transactions AS t ON c.id = t.custid
GROUP BY c.id
ORDER BY c.id
使用SUM
和GROUP BY
SELECT c.id, c.name, c.tel, SUM(t.books) as books, SUM(t.pens) AS pens, SUM(t.ruler) AS ruler
FROM customer AS c
LEFT JOIN transactions AS t ON c.id = t.custid
GROUP BY c.id
ORDER BY c.id
这样试试
select
`customer`.id,
`custmaster`.name,
`custmaster`.tel,
`transaction`.id,
sum(`transaction`.books) as books,
sum(`transaction`.pens) as pens,
sum(`transaction`.ruler) as ruler,
from `customer`
left join `transaction`
on `customer`.id=`transaction`.custid
Group by `customer`.id,`customer`.Name
ORDER BY `customer`.id ASC";
这样试试
select
`customer`.id,
`custmaster`.name,
`custmaster`.tel,
`transaction`.id,
sum(`transaction`.books) as books,
sum(`transaction`.pens) as pens,
sum(`transaction`.ruler) as ruler,
from `customer`
left join `transaction`
on `customer`.id=`transaction`.custid
Group by `customer`.id,`customer`.Name
ORDER BY `customer`.id ASC";
很好…为便于参考而设置表名快捷方式。很好…为便于参考而设置表名快捷方式。我需要2个分组依据吗?还是只需要按customer
进行分组。id就可以了。我对这两者进行了某种测试,两者都给出相同的结果。选择transaction.id
,没有意义,因为您正在聚合所有事务。@SykesTangSQL要求您必须在GROUP BY
子句中列出所有未聚合的列。但是MySQL允许您省略它们,因此您只需要定义组的列。我需要2个GROUP BY吗?或者我可以只按customer
进行分组。id就可以了。我会对这两个列进行排序测试,两者都会给出相同的结果。选择没有意义>transaction.id
,因为您正在聚合所有事务。@SykesTang Strict SQL说您必须在GROUP BY
子句中列出所有未聚合的列。但是MySQL允许您将它们省略,所以您只需要定义组的列。