doushi6932 2014-12-11 17:21
浏览 36
已采纳

通过JOIN查询单个查询中的多个表

I cannot quiet get using the JOIN clause around my head, even after I have ready multiple posts on the topic.

Here is my problem: At the moment I have 2 tables.

Users Table:

ID | Username | Password
1  |   Micky  |   123
2  |   Mouse  |   145

Questions Table:

Question ID| Question_Title   | Question      | Rating | Category ID | User ID |
    1      | Meaning of Life? | Same as Title |  100   |      2      |    1    |
    2      | Foo is love?     | Same as Above |   95   |      4      |    2    |

Now I simply want to run a query which will find a match in the title and the find out which user ID corresponds to that question and then get the name of the user, as well as the Question Title, Question and Rating then print them out.

So far I have:

"SELECT Question_Title, Question, Rating FROM Questions WHERE Question_Title LIKE  '%$Term%'";

This works as in it will get me the Question Title, Question and Rating from the table wherever it finds a match but how would I use JOIN so that it will also get me the Username from the Users table?

Also this is just early implementation I will in the future have a lot more tables that will require similar query so I need to understand how this works.

P.S: I know their are plenty of examples like this but I had trouble understanding them so if one of you kind souls could break it down and explain I would be grateful.

  • 写回答

2条回答 默认 最新

  • douci6541 2014-12-11 17:28
    关注

    Try this

     SELECT 
        u.username
        q.Question_Title, 
        q.Question, 
        q.Rating 
        FROM Questions q
        join Users u on u.id = q.userid
        WHERE q.Question_Title LIKE  '%$Term%'";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?