簡體   English   中英

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

[英]How do I get rows with value1 in column1 and value2 in column2 but value2 in column1 does not have value1 in column2?

我有一個名為contacts的表:

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

如何從該表中選擇其中user_id具有contact_id但感覺卻contact_id的行-我的意思是contact_id不具有user_id作為contact_id

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

   10295       10296

我可以使用以下命令選擇所有user_id10295行:

        $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

我怎樣才能做到這一點?

你可以做:

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

我不確定是否有聰明有效的方法直接在sql中直接執行此操作(當然是,請參見此答案 )。 我的方法是進行第二次查詢。 您的第一個查詢將獲取查詢用戶已添加的所有聯系人。 第二個查詢將執行相反的操作,並查找添加了我們要查詢的用戶的所有用戶。

然后比較這兩個列表,在這種情況下,您希望第二個列表中的所有元素都不在第一個列表中。

// 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM