简体   繁体   中英

MySQL group by without column name

I have a table contains user infos.

mysql> desc accounts;
+-------------+------------+------+-----+---------+----------------+
| Field       | Type       | Null | Key | Default | Extra          |
+-------------+------------+------+-----+---------+----------------+
| cid         | int(11)    | NO   | PRI | NULL    | auto_increment |
| username    | text       | YES  |     | NULL    |                |
| password    | text       | YES  |     | NULL    |                |
| mysignature | text       | YES  |     | NULL    |                |
| is_admin    | varchar(5) | YES  |     | NULL    |                |
+-------------+------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)

Normal group by statement always follows by one or more column names like below:

select * from accounts group by cid;

Just an example, in general group by works with Aggregate functions like sum() .

I have found some follows by an expression without column names which I cant understand:

mysql> select username from accounts group by now();
+----------+
| username |
+----------+
| admin    |
+----------+
1 row in set (0.00 sec)

I am new in MySQL. How does this query work ? Thanks.

In fact it's expression. It compares expression results instead of column values for the grouping.

now() function with the group by is not so effective.

It will always return the first row from the selected data.

You always need to specify the column name in the group by clause in query. Here are link of tutorial of group by. It specify that which aggregate function you can use with group by.

now() with group by return that will select the data from the query and match the first and it will be first row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM