I have this query:
SELECT
FIELD1, FIELD2, FIELD3, FIELD4, FIELD5
FROM
MYTABLE
WHERE
FIELD1 = .... AND
FIELD2 = .... AND
FIELD3 = ....
GROUP BY
FIELD4
;
Note that the only thing I changed are the names of the fields and the table. My query does have 5 fields in the SELECT
statement and 1 table in the FROM
section. The WHERE
and the GROUP BY
sections also looks exactly like that: 3 fields with equals condition.
The fields FIELD1
, FIELD2
and FIELD3
are both PKs and indexes.
The problem: The query takes almost 8 seconds to finish (and it returns around 30 rows).
The question: Is there any way I can speed up the query, that isn't server related (increasing cache, running the database in a more powerful server, etc...)?
EDIT:
Fields declaration:
FIELD1: VARCHAR(2)
FIELD2: VARCHAR(3)
FIELD3: VARCHAR(7)
FIELD4: VARCHAR(4)
FIELD5: VARCHAR(5)
EDIT 2:
Output of SHOW INDEX
: http://ibin.co/1LSSwvr0CVpX
EDIT 3:
Output of EXPLAIN
:
select_type: SIMPLE
table: MYTABLE
type: ALL
possible_keys:
key:
key_len:
ref:
rows: 2081601
Extra: Using where; Using temporary; Using filesort
EDIT 4:
Example data:
Chicago = 1 (neighborhoods 001, 002, 003) (neighborhood zone 1, 2, 3) (postal code 10, 20, 30)
NY = 2 (neighborhoods 001, 002, 003) (neighborhood zone 1, 2, 3)(postal code 10, 20, 30)
Los Angeles = 3 (neighborhoods 001, 002, 003) (neighborhood zone 1, 2, 3)(postal code 10, 20, 30)
Data
1 001 1 10
1 002 1 10
1 002 1 20
1 002 2 20
1 003 1 30
2 001 1 10
2 002 1 20
3 001 1 10
3 002 1 10
3 002 2 20
What I do:
Search all postal codes that match TOWN == 1 (Chicago) AND Neighborhood == 001 AND ZONE == 1 and then GROUP BY the postal code. I hope this makes it clear.
problem seems with your searching method just inclosed your values like field1='value' as these are varchar and you are using with out quotes. By this your query will use index and you get performance.
Note: There is no need to use index as mysql do it its own.