MySQL query to check mutual values

I have a MySQL DB that resembles the following:

    uid          suid
    1              5
    1              6
    2              5
    5              1
    5              2

I give him the only unique "uid" through the POST method, name it 1. What I need to do is return all "suid", where $ uid "has" suid AND suid (as uid) "has" $ uid (like suid. ) So, in the above example, the script should return only 5.

I know my first step is

    "Select * FROM table Where uid = $uid"

then maybe i need to skip the results and query DB WHERE suid = $ uid. I do not know how to execute the second request. Any suggestions?

+4
source share
2 answers

- , , uid suid suid .

SELECT
    t1.suid
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.uid  = t2.suid AND
       t1.suid = t2.uid
WHERE
    t1.uid = 1

, WHERE, :

uid | suid  (uid not selected)
1   | 5
5   | 1

WHERE , , uid, .

:

Rextester

+1

:

    $uid = $_POST["UID"];

    $myquery = "SELECT * FROM Table WHERE uid = '$uid'";

    $result = $conn->query($myquery);
     if ($result->num_rows > 0) {

       while($row = $result->fetch_assoc()) {

        $myquery2 = "SELECT * FROM Table WHERE uid = '" . $row['suid'] . "' AND suid = '$uid'"; 
        $result2 =  $conn->query($myquery2);   

        if ($result2->num_rows > 0) {

            while($row = $result2->fetch_assoc()) {

                    echo $row["uid"].
              "!@#$";

        }
        }       
    }
}

    $conn->close();
    ?>

, , .

+1

Source: https://habr.com/ru/post/1684173/


All Articles