mysql - SQL 连接 : Just not able to understand them

标签 mysql join

现在,我知道这个与JOIN 相关的问题已经被问过很多次了。我经历了很多。但我仍然不清楚。我也读了这些文章:http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins#_commentshttp://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 匹配)。

现在,两个问题:

  1. 这个查询正确吗?它会给我想要的结果吗?

  2. 我应该在代码中写什么来代替 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/

相关文章:

sql - 为什么在左外连接中需要 'ON' 子句

mysql - 使用内连接连接同一数据库中超过 5 个表

sql - 如何在 Ruby on Rails Controller 中手动连接两个具有不同属性名称的不同表

mysql - MySQL 查询中的每一行都需要一个序列号

mysql - 查找表中的区间

添加 PHP 扩展时出现 PHP 错误

mysql - 优化用于查找两个表之间匹配的MySQL查询

mysql - 当某些表为空时如何进行多重连接

mysql - PHP mySQL 查询,加入另一个表但需要获取所有行

php - MySQL计数查询不起作用,但它显示记录列表