现在,我知道这个与JOIN
相关的问题已经被问过很多次了。我经历了很多。但我仍然不清楚。我也读了这些文章:http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins#_comments和 http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html但没有,它仍然没有帮助。
我在数学上理解静脉图,但无法掌握 JOIN
背后的基本概念。
假设我有两个表。
tbl_book描述:
| 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')`
然后 UNION
此表与 SOMETHING
(将 authorName 与 $searchterm 匹配)。
现在,两个问题:
这个查询正确吗?它会给我想要的结果吗?
我应该在代码中写什么来代替
SOMETHING
。我想我将不得不JOIN
两个表(不确定)。也不知道怎么加入。
感谢帮助。
最佳答案
如果您只使用一个搜索词进行搜索,那么您的查询可能看起来像
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%'
如果将 searchterm
替换为“Tom”,您将得到
| BOOKID | BOOKNAME | BOOKREVIEW | AUTHORID | AUTHORNAME | ------------------------------------------------------------ | 1 | SQL Basics | Cool | 1 | Tom |
现在,如果它是“好”的话
| BOOKID | BOOKNAME | BOOKREVIEW | AUTHORID | AUTHORNAME | ------------------------------------------------------------- | 2 | PHP Basics | Good | 2 | Jerry | | 4 | HTML Basics | Very Good | 3 | Phil |
这是 SQLFiddle 演示
关于mysql - SQL 连接 : Just not able to understand them,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17078952/