如何获取第1列的value1和第2列的value2但第1列的value2在第2列中没有value1的行?

时间:2019-06-09 23:52:38

标签: php mysql

我有一个名为contacts的表:

user_id     contact_id
10294       10295
10294       10293
10293       10294
10295       10296
10296       10294
10297       10296
10298       10295
10295       10294
10293       10297

我如何从该表中选择user_idcontact_id但感觉却不满意的行-我的意思是contact_id没有user_id作为contact_id

例如,在上述情况下,$user_id10295。我要的行是

   10295       10296

我可以选择所有带有user_id作为10295的行:

        $sql = "SELECT * FROM contacts 
        WHERE user_id = ?";  

        $stmt2 = $con->prepare($sql) or die(mysqli_error($con));
        $stmt2->bind_param('i', $user_id) or die ("MySQLi-stmt binding failed ".$stmt2->error);
        $stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);

        $privateReviews = $stmt2->get_result(); 

它会给我:

10295       10296
10295       10294

但是我只想找10295 10296

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以这样做:

select *
from contacts
where user_id = ?
  and (user_id, contact_id) not in (
  select contact_id, user_id from contacts
)

答案 1 :(得分:1)

我不确定是否有一种聪明而有效的方法可以直接在sql中直接执行此操作(确定是,请参见this answer)。我的方法是进行第二次查询。您的第一个查询将获取查询用户已添加的所有联系人。第二个查询将进行相反的操作,并查找所有已添加我们要查询的用户的用户。

然后比较这两个列表,在这种情况下,您希望第二个列表中的所有元素都不在第一个列表中。

// This line is changed
$sql = "SELECT contact_id FROM contacts 
WHERE user_id = ?";

// these lines are unchanged
$stmt2 = $con->prepare($sql) or die(mysqli_error($con));
$stmt2->bind_param('i', $user_id) or die ("MySQLi-stmt binding failed ".$stmt2->error);
$stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);

// changed this variable name
$usersThisUserHasAdded = $stmt2->get_result(); 

//new lines
$sql = "SELECT user_id FROM contacts 
WHERE contact_id = ?";
$stmt3 = $con->prepare($sql) or die(mysqli_error($con));
$stmt3->bind_param('i', $user_id) or die ("MySQLi-stmt binding failed ".$stmt3->error);
$stmt3->execute() or die ("MySQLi-stmt execute failed ".$stmt3->error);

$usersWhoHaveAddedThisUser = $stmt3->get_result();

$usersWhoHavedAddedThisUserUnreciprocated = array_diff($usersWhoHaveAddedThisUser, $usersThisUserHasAdded);

// $usersWhoHavedAddedThisUserUnreciprocated should now have all the users we are looking for, if you want this in a different format or as some selection of rows you should be able to format it yourself with the original nuser ID or query the rows again using this list