SQL JOIN: Just not able to understand them

夙愿已清 提交于 2021-02-11 05:55:59

问题


Now, I know know this question related to JOIN have been asked many times. I went through many of them. But it still isn't clear to me. I read these aricles too: http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins#_comments and http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html but no, it still didn't help.

I do understand the Vein diagrams mathematically but not able to grab basic concept behind JOIN.

Suppose I have two tables.

tbl_bookdescription:

| BOOKID |    BOOKNAME | BOOKREVIEW | AUTHORID |
------------------------------------------------
|      1 |  SQL Basics |       Cool |        1 |
|      2 |  PHP Basics |       Good |        2 |
|      3 | AJAX Basics |     Superb |        2 |
|      4 | HTML Basics |  Very Good |        3 |

tbl_authordescription

| AUTHORID | AUTHORNAME |
-------------------------
|        1 |        Tom |
|        2 |      Jerry |
|        3 |       Phil |

I want to script a search engine for my website

So, when the user enters Tom as $searchTerm, I want the program to return the name of the book which is written by Tom. And at the same time, the user can also enter Good. This time the query should again return the name of the book. So, I thought to do something like this

SELECT bookname FROM tbl_bookdescription MATCH(bookReview) AGAINST('$searchTerm')` 

and then UNION this table with SOMETHING (something which matches authorName against $searchterm).

Now, two questions:

  1. Is this query right? Will it give me the desired results?

  2. WHat should I write in the code in place of SOMETHING. I think I will have to JOIN both the tables(not sure). And don't know how should I join.

Help appreciated.


回答1:


If you search using only one search term then your query might look like

SELECT b.*, a.*
  FROM tbl_bookdescription b JOIN tbl_authordescription a
    ON b.authorID = a.authorID
 WHERE b.bookName   LIKE '%searchterm%'
    OR b.bookReview LIKE '%searchterm%'
    OR a.authorName LIKE '%searchterm%'

If you replace searchterm with 'Tom' you'll get

| BOOKID |   BOOKNAME | BOOKREVIEW | AUTHORID | AUTHORNAME |
------------------------------------------------------------
|      1 | SQL Basics |       Cool |        1 |        Tom |

Now, if it's 'Good' then

| BOOKID |    BOOKNAME | BOOKREVIEW | AUTHORID | AUTHORNAME |
-------------------------------------------------------------
|      2 |  PHP Basics |       Good |        2 |      Jerry |
|      4 | HTML Basics |  Very Good |        3 |       Phil |

Here is SQLFiddle demo




回答2:


Try this query

SELECT 
    a.* 
FROM 
    tbl_bookdescription a
INNER JOIN 
    tbl_authordescription b
ON 
    a.authorid = b.authorid 
WHERE 
    b.authorname=''


来源:https://stackoverflow.com/questions/17078952/sql-join-just-not-able-to-understand-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!