一尘不染

SQL选择行如果其他表中不存在任何行

sql

我有一张users桌子和一张likes桌子。向用户显示随机的其他用户数据,并可以决定他喜欢还是不喜欢它。我正在为尚未评级的代理用户选择新的随机用户合作伙伴!

现在,我试图选择likes表中没有行的所有用户,并将执行用户user与已评级用户的关系评级partner

users表是一个标准的用户表,在likes我的列,iduserpartnerrelation

我正在使用Laravel Eloquent,但也可以使用原始sql。

我的尝试:

// $oUser->id is the acting user
$oSearch = Db_User::
              select( 'db_users.*', 'db_likes.*' )
              ->where( 'db_users.id', '<>', $oUser->id )
              ->where( 'db_likes.user', '=', $oUser->id )
              ->where( 'db_likes.relation', '<>', 'dislike' )
              ->where( 'db_likes.relation', '<>', 'like' )
              ->where( 'db_likes.relation', '<>', 'maybe' )
              ->join( 'db_likes', 'db_users.id', '=', 'db_likes.partner' );

这是错误的,因为通过此尝试我没有选择任何新用户。我认为是因为找不到任何行likes!他尚未评分时没有行,因此没有结果。这样对吗?

编辑:

$oSearch = Db_User::
              select( 'db_users.*' )
              ->where( 'db_users.id', '<>', $oUser->id )
              ->where( 'db_users.sex', '=', $strSex )
              ->whereRaw( "not exists ( select 1 from db_likes where db_likes.relation in ('dislike','like','maybe') and db_likes.user = " .$oUser->id . " and db_likes.partner = db_users.id )" );

错误:"{"error":{"type":"Illuminate\\Database\\QueryException","message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'IO8fMLYUPHfX1HrwkAWc2xqX' in 'where clause' (SQL: selectdb_users .* fromdb_users wheredb_users .id <> IO8fMLYUPHfX1HrwkAWc2xqX anddb_users.性别= w and not exists ( select 1 from db_likes where db_likes.relation in ('dislike','like','maybe') and db_likes.user = IO8fMLYUPHfX1HrwkAWc2xqX and db_likes.partner = db_users.id ) order by RAND() limit 1)","file":"\/Applications\/MAMP\/htdocs\/adamundeva- server\/adamundeva\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Connection.php","line":625}}"

**

最终解决方案:

**

$oSearch = Db_User::
              select( 'db_users.*' )
              ->where( 'db_users.id', '<>', $oUser->id )
              ->where( 'db_users.sex', '=', $strSex )
              ->whereRaw( "not exists ( select 1 from db_likes where db_likes.relation in ('dislike','like','maybe') and db_likes.user = '" .$oUser->id . "' and db_likes.partner = db_users.id )" );

阅读 176

收藏
2021-03-08

共1个答案

一尘不染

您可以not exists用来选择尚未与某个用户合作的所有用户

select * from
db_users dbu
where not exists (
    select 1 from db_likes dbl
    where dbl.relation in ('dislike','like','maybe') -- not sure if this is necessary
    and dbl.user = $oUser->id
    and dbl.partner = dbu.id
)

http://sqlfiddle.com/#!2/8c3bb9/6

2021-03-08