1

I'm trying to do a query in mysql

   SELECT *
FROM table_name1
WHERE codregister IN
    (SELECT register
     FROM tablename2
     WHERE city LIKE '%paris%')
ORDER BY date DESC

In table_name "codregister" is a primary key but in tablename2 "register" field column is a index (primary key on tablename2 is an autoincrement).

In the table_name1 doesn´t have matches with the tablename2 but the execution time of the query is to slow. Someone can recommend to improve the query?

3
  • It's slow because you have nested selections, so if you want to speed it up that would be the first place to look (using INNER JOIN or something to the effect). Commented Nov 18, 2013 at 12:08
  • time execution dude? I don't know who you're talking about... Commented Nov 18, 2013 at 12:22
  • Sorry, I've confused a word with my language. ;) Commented Nov 19, 2013 at 8:33

3 Answers 3

1

Check this considerable difference from csf answer

SELECT * 
FROM 
    table_a a 

    INNER JOIN 

    (SELECT register 
     FROM table_b 
     WHERE city like '%paris%') b
ON(a.codregister=b.register)
ORDER BY a.date

You're only projecting the only field of B that you need, and you are filtering B records before the join.

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

2 Comments

Thanks, your reply was useful to me, the execution time is more faster with your query.
One more question related, Is advisable always filter with a subquery the table that is joined even if the subquery not have like or where clause ?
1

Use JOIN instead , and make sure joining variables are indexed .

SELECT * FROM table_name1 a
JOIN tablename2 b on a.codregister = b.register
where b.city like '%paris%'
ORDER BY a.date  DESC

Also for any query you write try to use 'EXPLAIN' to find more about your query Ref : http://dev.mysql.com/doc/refman/5.0/en/explain.html

1 Comment

Thanks also for your reply. ;)
0

i agree with 0R10N Answer , filtering before join can make join faster . ThankI

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.