0

我目前正在开发一个需要搜索数据库表的网站,books_for_sale以匹配以下字段:isbn_10, isbn_13, name, author, publisher, description

每个字段都需要加权,以便可以按相关性对结果进行排序。

我想使用以下相关性乘数:

`isbn` = $searchTerm (30 relevance factor)
`isbn` LIKE $searchTerm% (25 relevance factor)

`name` = $searchTerm (20 relevance factor)
`name` LIKE $searchTerm% (15 relevance factor)
`name` LIKE %$searchTerm% (10 relevance factor)

`author` LIKE $searchTerm (22 relevance factor)
`author` LIKE $searchTerm% (14 relevance factor)
`author` LIKE %$searchTerm% (1 relevance factor)

`description` LIKE %$searchTerm% (2 relevance factor)
`publisher` LIKE %$searchTerm% (1 relevance factor)

当前表 SQL:

--
-- Table structure for table `books_for_sale`
--

CREATE TABLE IF NOT EXISTS `books_for_sale` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `seller_id` int(11) NOT NULL,
  `isbn_10` varchar(10) NOT NULL,
  `isbn_13` varchar(13) NOT NULL,
  `name` int(11) NOT NULL,
  `price` int(11) NOT NULL,
  `image_id` int(11) NOT NULL,
  `condition_id` int(11) NOT NULL,
  `author` varchar(50) NOT NULL,
  `publisher` varchar(50) NOT NULL,
  `description` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `isbn_10` (`isbn_10`),
  KEY `isbn_13` (`isbn_13`),
  KEY `name` (`name`),
  KEY `author` (`author`),
  KEY `seller_id` (`seller_id`),
  KEY `publisher` (`publisher`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

我试过谷歌搜索不同的功能,但没有找到任何有用的东西。如果有人可以帮助我,我将不胜感激,因为我对更高级的 MySQL 功能仍然很陌生。

PS 如果我应该重组我的表格以更好地支持这种类型的搜索功能,请告诉我。

4

1 回答 1

2

这是一个有效的语法:

SELECT * FROM books_for_sale

ORDER BY   30 * (`isbn_10` = '$searchTerm')
         + 30 * (`isbn_13` = '$searchTerm')
         + 25 * (`isbn_10` LIKE '$searchTerm%')
         + 25 * (`isbn_13` LIKE '$searchTerm%')
         + 20 * (`name` = '$searchTerm')
         + ...

小提琴:http ://sqlfiddle.com/#!2/2a935/3

请注意,这只是一个表达式,因此也将执行:

SELECT books_for_sale.* ,
(
    30 * (`isbn_10` = '$searchTerm')
  + 30 * (`isbn_13` = '$searchTerm')
  + 25 * (`isbn_10` LIKE '$searchTerm%')
  + 25 * (`isbn_13` LIKE '$searchTerm%')
  + 20 * (`name` = '$searchTerm')
  + ...
) as `relevance`

HAVING `relevance` > 10
ORDER BY `relevance` DESC
于 2012-11-14T12:04:33.210 回答