【发布时间】:2015-09-11 16:16:00
【问题描述】:
查询如下
select T.username,
sum(T.size) as totSize,
count(*) total,
count(case when T.type = 'facebook' then 1 else null end) as facebook,
count(case when T.type = 'instagram' then 1 else null end) as instagram,
count(case when T.type = 'device' then 1 else null end) as device
from (SELECT users.username, pictures.size, pictures.type from users left join pictures on pictures.user_id = users.id) as T
group by T.username
每个“用户”都有多个“图片”。 基本上,我想做的是:
- 左加入用户和图片表
- 按类型计算图片
- 总结图片大小
- 按用户分组
SQL 查询在应用于数据库时有效,但我需要在我的 CakePHP 3.0 应用程序中表示它。 我设法使用模型关联来 LEFT JOIN 表。在用户表中:
$this->hasMany('Pictures', [
'foreignKey' => 'user_id',
'joinType' => 'LEFT'
]);
然后在我的find方法中:
$options['contain'] = ['Pictures' => function ($q) {
return $q
->select(['user_id', 'size', 'type']);}];
$options['fields'] = array('Users.username');
$query = $this->find('all', $options);
如何继续查询?如果我尝试访问包含的数据(如“Pictures.type”),我会返回 SQL 错误,指出该列不在字段列表中。 我觉得这可能是错误的方法,但我想不出其他方法。
提前致谢!
【问题讨论】:
-
为什么是子选择,这与性能有关吗?如果没有测试,我可以想象非子查询的使用实际上可能更快。
标签: mysql sql cakephp cakephp-3.0 query-builder