Announcement

Announcement Module
Collapse
No announcement yet.

Order of results from WHERE LIKE

Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Order of results from WHERE LIKE

    Hello,

    In MySQL 4.1 database I have the following table:


    CREATE TABLE name_index ( id int(10) unsigned NOT NULL auto_increment, name varchar(200) NOT NULL default '', PRIMARY KEY (id), KEY name (name))


    It includes about 800.000 names ordered by importance. If I run the following query:


    SELECT * FROM name_index WHERE name LIKE 'sai%' LIMIT 10


    it returns 10 rows starting with "sai" but not in the same order like they are stored in the table.
    What I need is first 10 rows starting with "sai".

    If I run this query:


    SELECT * FROM name_index WHERE name LIKE 'sai%' ORDER BY id LIMIT 10


    it works but it is slow because MySQL uses filesort.

    Do you have any idea how to solve this? Any help is very appreciated.

    Thomas

  • #2
    Two suggestions:

    1. Do a "select [columns]" instead of "select *"

    2. Make the "name" field a full-text field, and avoid using LIKE

    Hope it helps!

    Comment


    • #3
      Thanks, but it doesn't solve the problem.
      I need the results orderd by id, but when I add "ORDER BY id" in the query, mysql uses filesort which is very slow.
      Any other idea?

      Comment


      • #4
        See if a "order by null" helps.

        Comment


        • #5
          Unfortunately not. It has the same effect like the query without ORDER BY.

          Comment


          • #6
            What you want is:

            ALTER TABLE name_index ADD INDEX name_index_ix_name_id (name, id);

            That will create a combined index for you.

            Which combined with your:

            SELECT name, id FROM name_index WHERE name LIKE 'sai%' ORDER BY id LIMIT 10

            should be fast enough for your needs.

            The trick is that the combined index has all the where columns in the index and the order by column is last.
            That gives mysql the chance to use the index to solve both the where part _and_ the order by.

            Comment


            • #7
              Thank you very much for your help! The explain-extra now reads "Using where; Using index; Using filesort" and the query really runs a little faster.

              Comment

              Working...
              X