Search code examples
phpsqlselectmedoo

sql select all users from table X which are not in comination on table Y


I'm fairly new to sql and am trying to get data from table X when the user is not in table Y with the combination of player id and world id AND the player access is 2.

Let me explain a little furter:

Table X (user table)

+-----------+----------+------------+
| uid       | access   |  more data |
+-----------+----------+------------+
| 1         | 2        |    ....    |
| 2         | 1        |    ....    |
| 3         | 2        |    ....    |
+-----------+----------+------------+

Table Y (worlds)

+-----------+-----------+
| userUuid  | worldUuid |
+-----------+-----------+
| 1         | 1         |
| 2         | 2         |
| 3         | 2         |
+-----------+-----------+

When I want to get all users which I can still add to world 1 I want to get the user info from user 3.

User 1 already is in world 1, user 2 does not have access level 2 and user 3 isn't in world 1 yet and does have access level 2.

I'm using medoo and this is my statement at the moment:

$database->select("User", [
    "[>]UserInWorld" => ["uid" => "userUid"]
], [
    "uid",
    "displayname",
    "surname",
    "email"
], [
    "AND" => [
        "worldUuid[!]" => $worldUuid,
        "access" => 2
    ]
]);

The worldUuid will be the world I want to get user to add for.

When use the ->debug() the query looks like this:

SELECT "uid","displayname","surname","email" 
FROM "User" 
LEFT JOIN "UserInWorld" ON "User"."uid" = "UserInWorld"."userUid" 
WHERE "worldUuid" != '4dafb8c0-57234ff2-03eb-af7f7a5e' 
AND "access" = 2

EDIT: I posted a sollution using medoo below


Solution

  • After a good night sleep I figured out how to do this using the medoo class

    $database->select("User", [
        "[>]UserInWorld" => ["uid" => "userUid"]
    ], [
        "uid",
        "displayname",
        "surname",
        "email"
    ], [
        "AND" => [
            "OR" => [
                "worldUuid[!]" => [$worldUuid],
                "worldUuid" => NULL
            ],
            "access" => 2
        ],
        "GROUP" => "uid"
    ]);
    

    Whereby the $worldUuid the world is I want to select users for.

    This will make the following sql statement:

    SELECT "uid","displayname","surname","email" FROM "User" 
    LEFT JOIN "UserInWorld" ON "User"."uid" = "UserInWorld"."userUid" 
    WHERE ("worldUuid" NOT IN ('1') OR "worldUuid" IS NULL) 
    AND "access" = 2
    GROUP BY "uid"
    

    This will select all (unique) user who do not have a world already OR are in the world I'm getting users for AND they have access level 2