查询MySql选择异常

时间:2014-05-25 02:42:36

标签: php mysql sql database

我正在做一个应用程序,我在查询中得到了用户在#34;房间内的信息。激活某个工具的用户在结果中不显示的位置。但即使我激活了工具,我也想让我的用户进入结果。

SELECT users.id, users.username, users.profile_pic, room_players.points 
FROM tools_by_user_by_room, users, room_players 
WHERE room_players.room = 0 AND room_players.user = users.id AND tools_by_user_by_room.user = users.id AND tools_by_user_by_room.room = room_players.room AND tools_by_user_by_room.tool = 2 AND tools_by_user_by_room.active != 1
ORDER BY points DESC;

好吧,假设房间有id = 0,我的用户ID为1,工具有id = 2。 即使我已激活(id = 2)工具(active = 1),我还需要做什么才能显示在结果中?

编辑:根据我的回答在评论中添加结构化查询(使用ANSI-92):

SELECT 
    users.id, 
    users.username, 
    users.profile_pic, 
    room_players.points 
FROM 
    room_players
        join users
            on room_players.user = users.id 
        join tools_by_user_by_room
            on tools_by_user_by_room.user = users.id 
            and tools_by_user_by_room.room = room_players.room
WHERE 
    room_players.room = 0 
    AND tools_by_user_by_room.tool = 2 
    AND tools_by_user_by_room.active != 1
ORDER BY 
    points DESC;

我的问题的答案是:

`SELECT 
    users.id, 
    users.username, 
    users.profile_pic, 
    room_players.points 
FROM 
    room_players
        join users
            on room_players.user = users.id 
        join tools_by_user_by_room
            on tools_by_user_by_room.user = users.id 
            and tools_by_user_by_room.room = room_players.room
WHERE 
    (room_players.room = 0 
    AND tools_by_user_by_room.tool = 2 
    AND tools_by_user_by_room.active != 1) 
    OR (room_players.room = 0 
    AND tools_by_user_by_room.tool = 2 
    AND tools_by_user_by_room.active = 1
    AND users.id = 1)
ORDER BY 
    points DESC;`

1 个答案:

答案 0 :(得分:1)

我重新格式化了代码,使其(至少对我而言)更容易理解您的代码。这是您的原始查询:

SELECT 
    users.id, 
    users.username, 
    users.profile_pic, 
    room_players.points 
FROM 
    room_players
        join users
            on room_players.user = users.id 
        join tools_by_user_by_room
            on tools_by_user_by_room.user = users.id 
            and tools_by_user_by_room.room = room_players.room
WHERE 
    room_players.room = 0 
    AND tools_by_user_by_room.tool = 2 
    AND tools_by_user_by_room.active != 1
ORDER BY 
    points DESC;

如果只是通过更改where条件,您现在无法获得所需的结果吗?

SELECT 
    users.id, 
    users.username, 
    users.profile_pic, 
    room_players.points 
FROM 
    room_players
        join users
            on room_players.user = users.id 
        join tools_by_user_by_room
            on tools_by_user_by_room.user = users.id 
            and tools_by_user_by_room.room = room_players.room
WHERE 
    room_players.room = 0 
    AND tools_by_user_by_room.tool = 2 
    AND tools_by_user_by_room.active = 1
    and user.id=1
ORDER BY 
    points DESC;