0

I have 2 tables in MySql

Table_A { pk_A VARCHAR 150 PRIMARY KEY, random_data } ~ 9500 rows
Table_B { pk_B VARCHAR 150, more_random_data } ~ 50000 rows

Relationship between them is one-to-many, pk_A will be found multiple times in Table_B on col pk_B.

My problem is:

  • if i enable indexing on pk_B , php/mysql CRUD works fine, but a JOIN or anyother query from command line involving both tables takes a long time

  • if i disable indexing on pk_B, php/mysql CRUD becomes laggish, but a JOIN or anyother query from command line involving both tables is instantaneous

How can i improve my database performance (i could modify my pk's from varchar to int(11)) but i wondered if there are other workarounds available

Thanks

8
  • 1
    Why you using varchar as primary key? Commented Sep 10, 2011 at 16:37
  • How are you joining the tables? The PKs should always be indexed, and foreign key columns should also be indexed for faster joins.
    – bfavaretto
    Commented Sep 10, 2011 at 16:41
  • What's the engine being used. There are different performance considerations between MyISAM and InnoDB. Commented Sep 10, 2011 at 16:45
  • @Book of Zeus : i didn't design the database, i migrated it from mdb to sql, what you're trying to say is to replace varchar with int
    – cristi _b
    Commented Sep 10, 2011 at 16:53
  • 1
    @cristi _b: Yes, absolutely. Integer are faster, they take up less space, and more importantly they are much quicker to compare. Commented Sep 10, 2011 at 16:55

1 Answer 1

2

A few things to speed up your queries. As the many comments suggest; you always want to keep your primary keys as small as is reasonable. A short string, say VARCHAR(10) won't cause you much pain, but much larger than that, you may want to use a surrogate key. This can be made more or less transparent by making the natural key be unique, but not in the primary key.

Table_A { pk_A VARCHAR 150 PRIMARY KEY, random_data } ~ 9500 rows Table_B { pk_B VARCHAR 150, more_random_data } ~ 50000 rows

Your schema should probably look a bit like this:

CREATE TABLE `Table_A` (
    `id` INTEGER AUTO_INCREMENT PRIMARY KEY,
    `A_name` VARCHAR(150) UNIQUE NOT NULL,
    -- other columns
) ENGINE = InnoDB;

CREATE TABLE `Table_B` (
    `id` INTEGER AUTO_INCREMENT PRIMARY KEY,
    `B_name` VARCHAR(150) UNIQUE NOT NULL,
    `A_id` INTEGER REFERENCES `Table_A`(`id`),
    -- other columns
) ENGINE = InnoDB;
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.