以下sql语句在mysql查询中有效,但在尝试在Laravel中执行以下操作时会出现错误SQLSTATE[42000]: Syntax error or access violation: 1055 'dashboard.m.id' isn't in GROUP BY (SQL: SELECT m.id, ....
:
$this->builder = DB::select
("SELECT m.id, m.member_num, m.first_name, m.last_name, COUNT(s.member_id) AS members
FROM sessions AS s
LEFT JOIN members AS m ON s.member_id = m.id
WHERE s.created_at >= :dateFrom
AND s.created_at < :dateTo
GROUP BY s.member_id",
['dateFrom' => "date('2017-11-01')",
'dateTo' => "date('2017-12-01')"]);
任何人都可以看到问题,因为它在mysql中正常工作。
我只是想获得sessions
的计数,并在member
member_id
个sessions
的详细信息
答案 0 :(得分:2)
您在Laravel中看到的错误与您选择未出现在SELECT *
FROM Student
LEFT JOIN fees ON student.Id = fees.StudentID
where fees.StudentID is null;
//intead of * you have to replace columns you want
// for your question text i think ID in student is primary key and StudentId
// in fees is foreign key so my answer is based on that only
子句中的非聚合列有关。它在MySQL中工作的原因显然是因为MySQL在关闭GROUP BY
的松散模式下运行,这可以容忍这种非标准语法。我怀疑你打算沿着这些方向使用查询:
ONLY_FULL_GROUP_BY
由于您正在聚合SELECT
m.id, m.member_num, m.first_name, m.last_name, s.member_count
FROM members m
LEFT JOIN
(
SELECT member_id, COUNT(*) AS member_count
FROM sessions
WHERE s.created_at >= :dateFrom AND
s.created_at < :dateTo
GROUP BY member_id
) s
ON m.id = s.member_id
表中的成员,并且仅计算该表中的字段,因此我建议在单独的子查询中进行聚合。然后,将其加入sessions
以检索完整的成员记录。
答案 1 :(得分:0)
要克服ONLY_FULL_GROUP_BY
issue,您可以使用ANY_VALUE()
来引用非聚合列。
DB::table('sessions')
->join('members', 'sessions.member_id', '=', 'members.id')
->select([
'members.member_num',
'members.first_name'
'members.last_name',
DB::raw('COUNT(sessions.member_id) AS members'),
DB::raw('ANY_VALUE(members.id) AS id'),
])
->where([
['sessions.created_at', '>=', date('2017-11-01')],
['sessions.created_at', '<', date('2017-12-01')]
])
->groupBy('sessions.member_id')
->get();