有没有办法在mysql查询中严格搜索字符串

时间:2015-08-20 08:34:56

标签: php mysql

假设我有一个表名'员工'如下:

 | name      | skills     |
 |------------------------|
 | john      | PHP, HTML  |
 | RIcky     | HTML5, PHP |
 | ROman     | HTML5, HTML|

我想严格搜索HTML。我试过了:

 select * from employee where skills like %HTML%  // show all result. But it should only display row with name 'john' and 'ROman'.

select * from employee where skills like %HTML5%  // show all result. But it should only display row with name 'RIcky' and 'ROman'.

如何直接从mysql查询中执行此操作。

更新:   我无法规范化表格,因为我在自动表单构建器中工作。意味着技能不是静态的。可能有任何价值观。与替代技能一样,用户可以选择其他领域。与调查形式biulder相同。

4 个答案:

答案 0 :(得分:3)

这适合使用。

SELECT * FROM employee WHERE FIND_IN_SET( 'HTML' , REPLACE(skills, SPACE(1), '') ) > 0;

答案 1 :(得分:1)

不完全是你要求的:
您可以normalize your database表,而不是在一个字段中存储复杂数据类型(字符串列表)创建三个表:

1)属性(技能)
2)对于“拥有”某些财产的实体(具有一定技能的员工)
3)a junction table,您可以在其中存储哪个实体具有哪些属性的信息(参考) 这样你的关系数据库系统有更好的机会使用索引来查找适当的数据(使用LIKE,字符串函数等在WHERE / ON子句中通常会导致全表扫描,为此你几乎不需要数据库 - 你可以用平面文件做到这一点几乎一样容易。)

E.g。 (虽然我没注意指数)

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
setup($pdo);

// Which employees have the skill 'HTML' ?
$query = "
    SELECT
        e.name
    FROM
        skills as s
    JOIN
        employee_skills as x
    ON
        s.id=x.id_skill
    JOIN
        employees as e
    ON
        x.id_employee=e.id
    WHERE
        s.name = 'HTML'
";
foreach( $pdo->query($query) as $row ) {
    echo $row['name'], "\r\n";
}

/* creating temporary test tables
   and inserting sample data
*/
function setup($pdo) {
    $pdo->exec('
        CREATE TEMPORARY TABLE employees (
            id int auto_increment,
            name varchar(32),
            primary key(id)
        )
    ');

    $pdo->exec('
        CREATE TEMPORARY TABLE skills (
            id int auto_increment,
            name varchar(32),
            primary key(id)
        )
    ');

    $pdo->exec('
        CREATE TEMPORARY TABLE employee_skills (
            id_employee int,
            id_skill int,
            unique(id_employee,id_skill)
        )
    ');

    $pdo->exec("
        INSERT INTO employees (id, name) VALUES
        (1, 'John'), (2,'Ricky'), (3,'Roman')
    ");

    $pdo->exec("
        INSERT INTO skills (id, name) VALUES
        (1, 'PHP'), (2,'HTML'), (3,'HTML5')
    "); 

    $pdo->exec("
        INSERT INTO employee_skills (id_employee, id_skill) VALUES
        (1, 1), (1,2),
        (2, 3), (2,1),
        (3, 3), (3,2)
    ");
}

答案 2 :(得分:-1)

尝试使用语音标记搜索您要搜索的文字:

select * from employee where skills like "%HTML%"
select * from employee where skills like "%HTML5%"

答案 3 :(得分:-1)

尝试基于REGEX的搜索

SELECT * FROM employee WHERE skills REGEXP '[[:<:]]HTML[[:>:]]'