Navneet Saini
Navneet Saini

Reputation: 944

SQL JOIN: Just not able to understand them

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.

Upvotes: 1

Views: 140

Answers (2)

peterm
peterm

Reputation: 92785

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

Upvotes: 1

Meherzad
Meherzad

Reputation: 8553

Try this query

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

Upvotes: 1

Related Questions