Home > Backend Development > PHP Tutorial > 求教两表关联,group和sum()的问题

求教两表关联,group和sum()的问题

WBOY
Release: 2016-06-20 12:31:43
Original
1093 people have browsed it

表如下:
我用TP,代码:
$info=$m->join('LEFT JOIN Table2on Table1.sku=Table2.sku')->field('Table1.name,Table1.sku,SUM(qty) as qty')->limit($page->firstRow.','.$page->listRows)->group('Table1.sku')->select();

// Table1
name           sku
zhangsan        aa
lisi            aa
xiaoming        bb
wanger          bb 

// Table2
sku             qty     location  
aa               20       A1
aa               25       A2 
aa               15       A3 
bb               2       A1
bb               2       A2 
bb               5       A3 

// 要得到如下
sku            qty
aa             60
bb              9


回复讨论(解决方案)

//只会框架坑死人select sku,sum(qty)qty from Table2 group by sku;
Copy after login

使用视图模型啊,你这样查询很不方便。使用视图模型,在模型的字段里"sum(字段)"=>'字段别名',D方法实例化模型,然后使用group(''Table1.sku),建议你先看看TP的视图模型,比join方法实用多了

select sku,sum(qty)qty from Table2 group by sku;

自动转为框架的吧。

3Q各位,已经解决了。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template