简体   繁体   中英

is there a better way to write this mysql select query?

SELECT jobs.*, user_table.* 
FROM jobs 
INNER JOIN user_table 
ON jobs.userid = user_table.userid WHERE 
(user_table.userid = ".$_SESSION['userid']." AND approved = 1) OR 
(user_table.userid = ".$_SESSION['userid']." AND approved = 2)

the way i used to have it, which didn't work was:

SELECT jobs.*, user_table.* 
FROM jobs INNER JOIN user_table 
ON jobs.userid = user_table.userid WHERE 
user_table.userid = ".$_SESSION['userid']." AND approved = 1 OR approved = 2

the first one works, but was wondering if there is a shorter way. the second one is shorter but doesn't work because it pulls records that approved equals 2 but don't have user id equaling the session userid.

You can try the IN syntax:

WHERE user_table.userid = ".$_SESSION['userid']." 
  AND approved IN (1,2)

If you create a compound index on usertable(userid, approved) this query will exploit that index (if approved is in user_table , which I can't tell from your question).

change

user_table.userid = ".$_SESSION['userid']." AND approved = 1 OR approved = 2

to

user_table.userid = ".$_SESSION['userid']." AND (approved = 1 OR approved = 2)

in the 2nd query

SELECT jobs.*, user_table.* 
FROM jobs JOIN user_table 
ON jobs.userid = user_table.userid WHERE 
user_table.userid = ".$_SESSION['userid']." AND (approved = 1 OR approved = 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM