I have a table shift_wise_traffic with following columns.
toll date shift car truck bus
1 2016-09-01 1 10 20 30
1 2016-09-01 2 15 25 35
1 2016-09-01 3 20 30 40
2 2016-09-01 1 5 10 15
2 2016-09-01 2 20 25 30
2 2016-09-01 3 35 40 50
1 2016-09-02 1 10 20 30
1 2016-09-02 2 10 20 30
1 2016-09-02 3 10 20 30
2 2016-09-02 1 10 20 30
2 2016-09-02 2 10 20 30
2 2016-09-02 3 10 20 30
Now I want to produce the output from shift_wise_traffic table group by
toll, date. And I have created a unique-index named shift_unique_index having two columns toll and date.
so instead of writing following query,
SELECT toll, date, SUM(car), SUM(truck), SUM(bus) FROM shift_wise_traffic
GROUP BY toll, date;
Can I use this query using shift_unique_index,
SELECT toll, date, SUM(car), SUM(truck), SUM(bus) FROM shift_wise_traffic
GROUP BY shift_unique_index;
Best Answer
GROUP BY
must have a list of columns, not an index name.INDEX
is an optimization, not a requirement.INDEX
may be useful for queries like this. (No index is likely to be useful for this particular query.)UNIQUE
versusINDEX
-- makes no difference in this context.UNIQUE
=INDEX
+ a constraint. ForINSERT
,UNIQUE
prevents duplicates.It feels like your
PRIMARY KEY
is(date, shift, toll)
in some order. Is it? If so, then changing the order toPRIMARY KEY(toll, date, shift)
might make yourGROUP BY
run a little faster. (But it might slow down other operations.)