开发者

mysql select for checking if a entry exist

开发者 https://www.devze.com 2023-03-12 05:50 出处:网络
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

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 ?


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.


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


Do:

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

This should fix your slowness.

0

精彩评论

暂无评论...
验证码 换一张
取 消