根据两个表减去记录

时间:2013-05-15 09:29:20

标签: mysql sql join

table1- testquestion

| ID |       QUESTION | ANSWER | STATUS |
-----------------------------------------
|  1 | first question |  demo1 |   done |
|  2 |    second que. |  demo2 |   done |
|  3 |      Third que |  demo3 |   done |
|  4 |     Fourth que |  demo4 |   done |

表2- Playedby

| ID | PLAY_ID | QUEST_ID | PLAYER_ANSWER |
-------------------------------------------
|  1 |       5 |        1 |             c |
|  2 |       4 |        1 |             a |
|  3 |       5 |        2 |             d |
|  4 |       4 |        2 |             b |
|  5 |       4 |        3 |             b |
|  6 |       4 |        4 |             c |
|  7 |       1 |        1 |             a |
|  8 |       3 |        1 |             c |
|  9 |       1 |        3 |             d |

我想获取那些没有被用户播放的问题。例如取用户1.
我想提取用户未玩过的问题1.我该怎么做?

1 个答案:

答案 0 :(得分:1)

请尝试LEFT JOIN,如下所示:

   SELECT q.*
     FROM testquestion q
LEFT JOIN Playedby p
       ON q.id = p.quest_id
      AND play_id = 1
    WHERE p.play_ID IS NULL

输出(Play_id = 1

╔════╦═════════════╦════════╦════════╗
║ ID ║  QUESTION   ║ ANSWER ║ STATUS ║
╠════╬═════════════╬════════╬════════╣
║  2 ║ second que. ║ demo2  ║ done   ║
║  4 ║ Fourth que  ║ demo4  ║ done   ║
╚════╩═════════════╩════════╩════════╝

See this SQLFiddle