简体   繁体   English

使用MySQL直接在查询中进行值检查

[英]Value check directly in the query using MySQL

I've the following table: 我有下表:

friends : 朋友们

id | user1 | user2   | status
1  | Jorge | Alisson | 3
2  | Lucas | Jorge   | 3

And to do a SELECT , I do (the variable $userLogged refers to the user logged in at the time): 要做一个SELECT ,我做(变量$userLogged指的是当时登录的用户):

SELECT user1, user2, status
FROM friends
WHERE user1 = '$userLogged' OR user2 = '$userLogged'

So, in PHP: 所以,在PHP中:

foreach($query as $q) {
    if($q["user1"] == $userLogged) {
        $userFriend = $q["user2"];
    } else {
        $userFriend = $q["user1"];
    }
}

Suppose the $userLogged is Jorge. 假设$userLogged是Jorge。 I want to get the friend ( $userFriend ), that is, which is not $userLogged (Alisson and Lucas, in case). 我想得到朋友( $userFriend ),即不是$userLogged (Alisson和Lucas,以防万一)。 Currently I do this check in the manner shown above, with PHP. 目前我使用PHP以上面显示的方式进行检查。 How can I do this directly in the query, thus saving this check in PHP? 如何在查询中直接执行此操作,从而在PHP中保存此检查? For ex.: SELECT user1 AND user2 <> '$userLogged' AS userFriend ... 例如: SELECT user1 AND user2 <> '$userLogged' AS userFriend ...

If you have an index on friends(user1, user2, status) and friends(user2, user1, status) , then the fastest way is: 如果您有friends(user1, user2, status)friends(user2, user1, status)的索引,那么最快的方法是:

SELECT user2 as `user`, status
FROM friends
WHERE user1 = '$userLogged' 
UNION ALL
SELECT user1, status
FROM friends
WHERE user2 = '$userLogged';

The index can be used for both subqueries, so this should be very fast. 索引可以用于两个子查询,因此这应该非常快。

SELECT
CASE WHEN user1 = '$userLogged' THEN user2
ELSE user1 END AS userFriend
FROM friends
WHERE user1 = '$userLogged' OR user2 = '$userLogged'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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