2

I have to run a query on a table where there are more than 10 million rows. The table structure is

user(varchar 100),
played(int 11),
won(int 11),
lost(int 11),
drawn(int 11),
user1(varchar 30),
user2(varchar 30).


Where
User - primary key
user1 - index
user2 - index

MySql database engine is MyISAM.

My problem is - When I run the below query it is taking more than 17 seconds.

SELECT * FROM h2hstats
WHERE (won+lost+drawn) > 5
  AND (user1 = '717054941' OR user2 = '717054941')

How can I reduce this execution time?

Will I make another indexing on (won+lost+drawn) columns?

6
  • Nope, because you do not search for them. Once the condition is met, you have access to the data. So it depends on the proper indexing for user1 and user2. And using numerical field types (INTEGER or BIGINT) for columns that contain only numerical values will also benefit performance. Commented Jul 29, 2016 at 9:07
  • 1
    never worked it this way before but maybe like this: AND 717054941 IN (user1,user2) Commented Jul 29, 2016 at 9:08
  • I recommend creating computed index on win+last+drawn ..dev.mysql.com/doc/refman/5.7/en/… i am not sure how two seperate indexes (user1,user2) can be used Commented Jul 29, 2016 at 9:11
  • @TheGameiswar "Page Not Found" on your link. Commented Jul 29, 2016 at 9:16
  • dev.mysql.com/doc/refman/5.7/en/… Commented Jul 29, 2016 at 9:23

1 Answer 1

2

First, if the user columns are numbers, then do not use single quotes for the constants. This can confuse the optimizer. This probably won't help your query (My SQL does a poor job of using indexes for OR), but it is worth trying.

Next, consider rewriting the query as:

SELECT *
FROM h2hstats
WHERE (won + lost + drawn) > 5 AND user1 = 717054941
UNION ALL
SELECT *
FROM h2hstats
WHERE (won + lost + drawn) > 5 AND user2 = 717054941 ;

MySQL will definitely use indexes for each of the subqueries. That should provide a performance boost.

(Note: This version assumes that user1 <> user2. If this is possible, you might want to use UNION rather than UNION ALL.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.