简体   繁体   中英

Querying more than 1 table in a single query via 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.

PS: 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.

Select a.* from a join b on a.id=b.a_id join c on c.b_id = b.id

在你的情况下是这样的:

SELECT Question_Title, Question, Rating,user.* FROM Questions join User on user_id=id WHERE Question_Title LIKE  '%$Term%'";

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%'";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM