[MySQL] Select a random WORD from table1 while excluding several WORDS from table 2

Discussion in 'Programming' started by Kellerkind, May 29, 2008.

  1. #1
    Hi,
    I have to query the db in the following scenario.

    I develop a little vocabulary learning application and have two tables. One with users and ids of words that they already know. The other table has all words in the db.

    I'm looking for a way to get a random word from the table WORDS for steve that is not one of the words he already knows.

    TABLE USERS

    user | id
    steve | 12
    steve | 14
    steve | 10
    lara | 10

    TABLE WORDS

    word | id
    fun | 7
    hard | 12
    cool | 10
    strong | 15

    It would be fantastic if anyone could help me with this one. Right now I first get all the words that Steve already knows and build a query ($protect). Then I use this query to get the random word.

    
    "SELECT * FROM vocdb WHERE item = 'Vocabulary' AND status = 'Approved' $protect ORDER BY RAND() LIMIT 1"
    Code (markup):
     
    Kellerkind, May 29, 2008 IP
  2. Freud2002

    Freud2002 Peon

    Messages:
    29
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Well I think the following query would do the job :

    SELECT w.* FROM words w, users u WHERE w.id<>u.id AND u.user='steve' ORDER BY RAND() LIMIT 1;

    I didn't test it but it should work.
     
    Freud2002, May 30, 2008 IP
  3. Kellerkind

    Kellerkind Active Member

    Messages:
    160
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #3
    Thanks! Works!
     
    Kellerkind, May 31, 2008 IP