1

i had a large databse and had to chec if a email is in a special group I had to tables.

first tabel called user

CREATE TABLE user ( uid int(10) NOT NULL AUTO_INCREMENT, kid int(3) NOT NULL, Email varchar(255) DEFAULT NULL, PRIMARY KEY (uid), KEY kid (kid) ) ENGINE=MyISAM 

and a table named group

CREATE TABLE `group` ( `vuid` int(10) NOT NULL AUTO_INCREMENT, `uid` int(3) NOT NULL, `vid` int(3) NOT NULL, PRIMARY KEY (`vuid`) ) ENGINE=MyISAM 

and for every insert i had a defined vid and a email Now i had to check, if a user with the uid is in the group vid.

select a.email,b.vuid from user a, group b where a.email=\''.$email.'\' and a.kid=' . $kid.' and b.vid=' . $vid . ' and a.uid = b.uid limit 1')

and check if the mysql_fetch_assoc is true or false.

BUT this is verry verry slow. is there a simple way to speed up ?

1
  • Why are you checking the email as well? Commented Jun 10, 2011 at 16:10

3 Answers 3

2

Rather than using a comma separated list of tables, try using a JOIN (in this case, INNER JOIN is your best bet since you want to check if records exist in both tables) with an ON clause. I have formatted your query and my changes are in capitals to make them stand out.

select a.email, b.vuid from user a INNER JOIN group b ON a.uid = b.uid where a.email=\''.$email.'\' and a.kid=' . $kid.' and b.vid=' . $vid . ' limit 1 

Next, check your indexes - make sure you have indexes on b.uid and a.kid. As a general rule, check your where clauses for values you can index; anything with unique values is a candidate.

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

Comments

1

If its slow, you might be missing indexes on either the lookup column or on the foreign key column.

4 Comments

Any column that you are using as a foreign key should be defined the same as the key in the foreign table and have an index. This way Mysql can handle the join quickly. If you don't do that, it will have to use slower table scan methods to join the tables.
:-/ could you please help me ? like ALTER TABLE group ADD FOREIGN KEY (uid) REFERENCES user(uid) ??
You dont need to add foreign key constraints, you just need to add indexes.
does i have to restartv the db ? because it istn faster... think slower
1

Do:

ALTER TABLE `group` ADD INDEX `uid`(uid); ALTER TABLE `user` ADD INDEX `email`(`Email`); 

This should fix your slowness.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.