如何在我的数据库中实现“搜索”?

时间:2012-04-18 19:12:04

标签: mysql database

所以我有大约6个表,每个表有6列,如地址,名称等。我必须实现一个搜索功能,用户输入一个'word',我必须搜索我的整个数据库(所有6个表)到找到单词,当找到单词时,应该从该表返回该特定行。不知道怎么办?

3 个答案:

答案 0 :(得分:1)

假设所有六个表都具有相同的列名,您可以使用此查询。

SELECT * FROM TABLE1 WHERE 
    col1 LIKE '%searchValue%' OR col2 LIKE '%searchValue%' OR 
    col3 LIKE '%searchValue%' OR col4 LIKE '%searchValue%' OR 
    col4 LIKE '%searchValue%' OR col6 LIKE '%searchValue%'
UNION ALL
SELECT * FROM TABLE2 WHERE 
    col1 LIKE '%searchValue%' OR col2 LIKE '%searchValue%' OR 
    col3 LIKE '%searchValue%' OR col4 LIKE '%searchValue%' OR 
    col4 LIKE '%searchValue%' OR col6 LIKE '%searchValue%'
UNION ALL
SELECT * FROM TABLE3 WHERE 
    col1 LIKE '%searchValue%' OR col2 LIKE '%searchValue%' OR 
    col3 LIKE '%searchValue%' OR col4 LIKE '%searchValue%' OR 
    col4 LIKE '%searchValue%' OR col6 LIKE '%searchValue%'
 and so on...

如果六个表具有不同的列名,您仍然可以使用union all但在必须重命名列之前,以便每个选择都返回相同的列名称

SELECT col_a as COL1, col_b as COL2, col_c AS COL3, col_d AS COL4, col_e AS COL5, col_f as COL6 FROM TABLE1 WHERE ....
UNION ALL
SELECT col_q as COL1, col_w as COL2, col_e AS COL3, col_r AS COL4, col_t AS COL5, col_y as COL6 FROM TABLE2 WHERE ....
etc..

如果上述两个查询都不能用于您的目的,您仍然可以使用单个查询,执行六个不同的select语句。

答案 1 :(得分:0)

使用LIKE子句和通配符。 (php的例子)

'Select * FROM Table_Nam WHERE column_Nam1 LIKE %' . $searchValue . '%'.
    'OR column_Nam2 LIKE %' . $searchValue . '%'.
    'OR column_Nam3 LIKE %' . $searchValue . '%'.
    'OR column_Nam4 LIKE %' . $searchValue . '%'.
    'OR column_Nam5 LIKE %' . $searchValue . '%'.
    'OR column_Nam6 LIKE %' . $searchValue . '%'.;

答案 2 :(得分:0)