我需要MySQL查询的帮助。这是我数据库的一部分:
+---------------+
| users |
+---------------+
| id |---
| username | | +-----------------+ +---------------------+
| first_name | | |users_in_projects| | regular_posts |
| last_name | | +-----------------+ +---------------------+
| email | | | id |-- | id |
| password | | | project_id | | | date |
| active | |----| user_id | | | size |
| created | +-----------------+ |---| users_in_project_id |
| modified | +---------------------+
| group_id |
+---------------+
和协会:
User hasMany UsersInProject
UsersInProject belongsTo User
UsersInProject hasMany RegularPost
RegularPost belongsTo UsersInProject
我想要的是结果表:
每个月的常规帖子的 username
和summary
大小,例如2010年:
username 2010-01 2010-02 2010-03 2010-04 2010-05 2010-06 2010-07 2010-08 2010-09 2010-10 2010-11 2010-12
foo 0.75 0.75 1 1 1 0.5 0.75 0.75 0.75 0.75 0.75 0.75
bar 0.5 0.5 0.5 0.5 1 0.75 0.75 1 1 1 1 1
...
或数组如:
Result => array (
[0] => array (
user.id => 1
user.username => foo
RegularPost => array (
[0] => array (
date => 2010-01
size => 0.75
)
[1] => array (
date => 2010-02
size => 0.75
)
...
)
)
[1] => array (
user.id => 2
user.username => bar
RegularPost => array (
[0] => array (
date => 2010-01
size => 0.5
)
[1] => array (
date => 2010-02
size => 0.5
)
...
)
)
...
)
我可以为一个用户编写查询,但是每个用户都不会。
$results = $this->User->UsersInProject->RegularPost->find('all', array(
'recursive' => 0,
'fields'=> array(
'RegularPost.id',
'RegularPost.date',
'SUM(RegularPost.size) AS size',
),
'conditions' => array(
'UsersInProject.user_id' => $id,
'RegularPost.date like' => '2010%',
),
'group' => array('RegularPost.date')
));
SELECT
`RegularPost`.`date`,
SUM(`RegularPost`.`size`) AS size
FROM
`regular_posts` AS `RegularPost`
LEFT JOIN
`users_in_projects` AS `UsersInProject`
ON
(`RegularPost`.`users_in_project_id` = `UsersInProject`.`id`)
WHERE
`UsersInProject`.`user_id` = 1 AND `RegularPost`.`date` like '2010%'
GROUP BY
`RegularPost`.`date`;
结果:
+------------+---------+
| date | size |
+------------+---------+
| 2010-01-01 | 0.75000 |
| 2010-02-01 | 0.75000 |
| 2010-03-01 | 0.75000 |
| 2010-04-01 | 0.75000 |
| 2010-05-01 | 0.75000 |
| 2010-06-01 | 1.00000 |
| 2010-07-01 | 0.75000 |
| 2010-08-01 | 0.75000 |
| 2010-09-01 | 1.00000 |
| 2010-10-01 | 0.75000 |
| 2010-11-01 | 0.75000 |
| 2010-12-01 | 1.00000 |
+------------+---------+
请帮忙。
答案 0 :(得分:0)
您是否尝试过这样做...从where子句中删除用户ID并将其添加到group by子句中?
SELECT
`RegularPost`.`date`,
SUM(`RegularPost`.`size`) AS size
FROM
`regular_posts` AS `RegularPost`
LEFT JOIN
`users_in_projects` AS `UsersInProject`
ON
(`RegularPost`.`users_in_project_id` = `UsersInProject`.`id`)
WHERE
`RegularPost`.`date` like '2010%'
GROUP BY
`UsersInProject`.`user_id`, `RegularPost`.`date`;