bedezign / yii2-audit

Yii2 Audit records and displays web/cli requests, database changes, php/js errors and associated data.
https://bedezign.github.io/yii2-audit/
Other
193 stars 111 forks source link

Database Exception on group by with alias on SQL Server #261

Closed filipe1309 closed 4 years ago

filipe1309 commented 5 years ago

Hi everyone,

Problem:

After running the migrations on a SQL Server database, and accessing the audit page, i've got the followings error:

SQLSTATE[42S22]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'day'.
The SQL being executed was: SELECT COUNT(DISTINCT id) as count, [created] AS [day] FROM [oac_audit_entry] WHERE [created] BETWEEN '2019-05-21 00:00:00' AND '2019-05-27 23:59:59' GROUP BY [day]

Error Info: Array
(
    [0] => 42S22
    [1] => 207
    [2] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'day'.
)

Platform: yii 2.0.16 php 5.6.40 windows server

Solution:

The reason of that error is that the GROUP BY is executed before the SELECT clause in SQL Server, and because of that the alias "day" doesn't exist yet.

One solution is to switch the groupBy parameter, from "day" to "created", in the following files:

References: https://stackoverflow.com/questions/3841295/sql-using-alias-in-group-by/3841804 https://social.msdn.microsoft.com/Forums/sqlserver/en-US/70efeffe-76b9-4b7e-b4a1-ba53f5d21916/order-of-execution-of-sql-queries?forum=transactsql