I have a query in MYSQL like this (simplified) :
SELECT col1, SUM(DISTINCT col2) AS S
FROM tbl1
WHERE col1='abbc'
GROUP BY col1
ORDER BY S ASC
I know that an index on col1 would be useful for that kind of query. I would like to know if a covering index on (col1, col2) would be more usefull or if it doesnt make any difference.
In MySQL, an index can be created on a table when the table is created with CREATE TABLE command. Otherwise, CREATE INDEX enables to add indexes to existing tables. A multiple-column index can be created using multiple columns. The indexes are formed by concatenating the values of the given columns.
The statement to create index in MySQL is as follows: CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name USING [BTREE | HASH | RTREE] ON table_name (column_name [(length)] [ASC | DESC],…) In above statement UNIQUE specify that MySQL will create a constraint that all values in the index must be distinct.
Starting from version 8.0. 13, MySQL supports functional indexes. Instead of indexing a simple column, you can create the index on the result of any function applied to a column or multiple columns.
i try it , it seems different and more usefull
without distinct
SELECT col1, SUM(col2) AS S
FROM tbl1
WHERE col1='abbc'
GROUP BY col1
ORDER BY S ASC;
distinct
SELECT col1, SUM(distinct col2) AS S
FROM tbl1
WHERE col1='abbc'
GROUP BY col1
ORDER BY S ASC;
SQL Fiddle
it's no different
SQL Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With