如何在字段组合中搜索数据

时间:2013-03-13 11:51:30

标签: php mysql

我有一个带有first_name和last_name的学生表。当我在名字或姓氏上应用搜索时,它会给我正确的记录,但是当我用完整的名字搜索时,它不会返回任何东西。这是我的查询

SELECT 
  `student_personal_info`.`spi_id` AS `sid`, 
  `student_personal_info`.`spi_first_name` AS `fname` 
FROM 
  `student_personal_info` 
WHERE 
 ((spi_first_name like '%test developer%') OR (spi_last_name like '%test developer%') 
ORDER BY 
 `spi_first_name` ASC

有没有办法让它可以用两种场组合进行搜索。

如果我们输入名字。中间名和姓,但是如果名字和姓氏不是中间名,则不会提取记录。

SELECT `student_personal_info`.`spi_id` AS `sid` , `student_personal_info`.`spi_first_name` AS `fname`
FROM `student_personal_info`
WHERE (
spi_scholar_no LIKE '%amir hussain khan%'
)
OR (
CONCAT( spi_first_name, ' ', spi_middle_name, ' ', spi_last_name ) LIKE '%amir hussain khan%'

我也试过这个,但它仅用于完全匹配。

SELECT `student_parents_info`.`spri_spi_id` AS `sid`
FROM `student_parents_info`
WHERE (MATCH (spri_first_name, spri_middle_name, spri_last_name) AGAINST ('Pramod Kumar Sharma*' IN BOOLEAN MODE ) )
ORDER BY `spri_first_name` ASC
LIMIT 0 , 30

请提供任何其他建议。

5 个答案:

答案 0 :(得分:1)

尝试使用concat()..

进行搜索
SELECT `student_personal_info`.`spi_id` AS `sid` , `student_personal_info`.`spi_first_name`    AS `fname`
FROM `student_personal_info`
  WHERE CONCAT( spi_first_name, ' ', spi_middle_name, ' ', spi_last_name ) LIKE '%test%'
ORDER BY `spi_first_name` ASC

它总是适合我。

答案 1 :(得分:0)

试试这个

SELECT `student_personal_info`.`spi_id` AS `sid`, `student_personal_info`.`spi_first_name` AS `fname` 
FROM `student_personal_info`
WHERE 
    ((spi_first_name like '%amir khan%') OR (spi_last_name like '%test develope%'))
ORDER BY `spi_first_name` ASC

你错过了')'

答案 2 :(得分:0)

您是否收到全名来执行搜索?或者你总是得到2个单独的(名字和姓氏)?

如果您获得一个全名字符串,请更改您的查询以连接名字和姓氏,并使用

GROUP BY HAVING(full_name LIKE %search_term%) 

如果你得到两个单独的字符串,只需将名字LIKE测试之间的OR更改为AND。

答案 3 :(得分:0)

尝试使用CONCAT:

SELECT
  `student_personal_info`.`spi_id` AS `sid`,
  `student_personal_info`.`spi_first_name` AS `fname`
FROM
  `student_personal_info`
WHERE 
  CONCAT(spi_first_name, ' ', spi_last_name) LIKE '%test develope%'
ORDER BY
 `spi_first_name` ASC

答案 4 :(得分:0)

使用php将test develope拆分为testdevelope,然后按以下方式编写查询:

$first = 'test';
$last  = 'develope';

$query = "SELECT `student_personal_info`.`spi_id` AS `sid`, `student_personal_info`.`spi_first_name` AS `fname` FROM `student_personal_info` WHERE 
(spi_first_name like '%".$first."%') OR (spi_last_name like '%".$last."%') 
ORDER BY `spi_first_name` ASC";

如果您有两个以上的字词,请拆分字词并创建动态where查询。