如何比较记录并在mysql中的同一个表的第三列中选择它们

时间:2016-11-27 02:13:35

标签: mysql join cakephp-3.x

表Interest_log

    Id  user_id  user_id_interested     
------  -------  ------------------  
     3        2                   3   
     5        3                   2   
     6        6                   2   
     7        6                   3   
     8        7                   2    
     9        2                   6 

我正在选择user_id_interested = 2的用户 非常简单     选择a.user_id,a.user_id_interested     来自interest_log a     其中a.user_id = 2;

当我选择user_id_interested = 2的用户时,在新列中,我选择那些也喜欢回到喜欢他的用户的user_id。

期待结果

     Id  user_id  user_id_interested     bUser_id
------  -------  ------------------     ----------- 
     5        3                   2       null
     6        6                   2        2
     8        7                   2       null

这是关于谁喜欢用户2和 在bUserId中,第一行和第三行具有null,而第二行具有值2,因为user_id 2也喜欢user_id 6但是用户2不喜欢用户3,7因此存在空

我写了这个查询

SELECT a.user_id ,a.user_id_interested , b.user_id AS bUserId
FROM interest_log a
LEFT OUTER JOIN interest_log b
ON a.user_id_interested = b.user_id
WHERE a.user_id_interested =2
AND b.user_id = a.user_id_interested

但是它给出了以下结果

user_id  user_id_interested  bUserId  
-------  ------------------  ---------
      3                   2          2
      3                   2          2
      6                   2          2
      6                   2          2

任何想法应该在这里使用什么连接。 如果有人能说出应该使用什么连接以及如何在cakephp 3中加入它,我真的很感激。

1 个答案:

答案 0 :(得分:0)

您可以尝试加入子查询:

SELECT a.user_id ,a.user_id_interested, b.bUserId
FROM interest_log a
LEFT JOIN (
    SELECT a.user_id_interested AS bUserId FROM interest_log a WHERE a.user_id = 2
) as b ON a.user_id = b.bUserId
WHERE a.user_id_interested = 2

该查询要求查找对user_id 2感兴趣的用户,然后将bUserId与一个子查询结合,该子查询仅要求查找对user_id 2感兴趣的用户。每次都匹配时结果,每次都没有NULL。

这将为您提供一个与您想要的表类似的表:

+---------+--------------------+----------+
| user_id | user_id_interested | bUserId |
+---------+--------------------+----------+
|       3 |                  2 | 3        |
|       6 |                  2 | 6        |
|       7 |                  2 | NULL     |
+---------+--------------------+----------+

要在Cakephp 3中编写此代码:

$id = 2;
$query = $this->InterestLog->find()
    ->select([
        'InterestLog.user_id',
        'InterestLog.user_id_interested',
        'b.bUserId'
    ])
    ->join([
        'b' => [
            'table' => '(SELECT InterestLog.user_id_interested as bUserId FROM interest_log InterestLog WHERE InterestLog.user_id = ' . $id . ')',
            'type' => 'LEFT',
            'conditions' => 'InterestLog.user_id = b.bUserId'
        ]
    ])
    ->where([
        'InterestLog.user_id_interested' => $id
    ]);