We have a table for "trips". A trip is organized by a user. A trip can be viewed online by people. A trip can be part of a group of trips. Now, I want to get all trips by group but want to SUM the "views" of a trip at the same time.
SELECT *, SUM(tripView) AS views FROM trip WHERE tripGroup != 0 AND tripOrganizerUserId = '1' GROUP BY tripGroup
With this, I get wrong numbers as "views". So how can I, in the query, without making a "SELECT SUM()" in every while-element, sum the views in this query?
As axiac points out in his comment, 'select *' and 'group by' in the same SQL statement is actually illegal. However, MySql's parser is broken when it comes to group by and allows it; I have no idea what it actually calculates but it's wrong.
正如他在評論中指出的那樣,在同一個SQL語句中,“select *”和“group by”實際上是非法的。但是,MySql的解析器在分組時被破壞並允許它;我不知道它實際計算的是什么,但這是錯誤的。
What you need to do is select what it needs to group by. So your SQL would be:
SELECT tripGroup, SUM(tripView) AS views FROM trip WHERE tripGroup != 0 AND tripOrganizerUserId = '1' GROUP BY tripGroup
MySql will parse this correctly, and should give you the answer you expect.