[英]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. 第二个较短,但不起作用,因为它会拉取已批准等于2但用户ID不等于会话userid的记录。
You can try the IN syntax: 您可以尝试IN语法:
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). 如果您在usertable(userid, approved)
上创建复合索引, usertable(userid, approved)
该查询将利用该索引(如果approved
在user_table
approved
,则无法从您的问题中得知)。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.