用于在表中搜索字符串的SQL查询?

时间:2016-03-16 19:53:50

标签: mysql sql database

您好我想在存储在mysql数据库中的表中搜索特定字符串。表格结构如下: -

SELECT * from `table` where day='Thursday' AND `9-10`='DA6220' OR `10-11`='DA6220' OR `11-12`='DA6220' 
            OR `12-1`='DA6220' OR `1-2`='DA6220' OR `2-3`='DA6220' OR `3-4`='DA6220'

我想要一天一天地搜索字符串。对于前者如果当天是星期四并且代码是DA6220,它应该返回空集,因为星期四所有时段都没有字符串。

我已经创建了一个sql查询但它没有按预期工作。请提供一种方法。

SQl查询: -

<script src="includes/jquery/jquery-1.12.1.min.js"></script>
<script src="includes/bootstrap/js/bootstrap.min.js"></script>

3 个答案:

答案 0 :(得分:2)

SELECT * from `table` where day='Thursday' AND (`9-10`='DA6220' OR `10-11`='DA6220' OR `11-12`='DA6220' 
            OR `12-1`='DA6220' OR `1-2`='DA6220' OR `2-3`='DA6220' OR `3-4`='DA6220')

首先评估你的AND。请尝试以上

答案 1 :(得分:1)

已经给出了问题的答案,但是当我查看您的数据时,我发现了一些可以让您的生活更轻松并增加可能性的东西: 您最好创建一个 VIEW

首先,我稍微调整了您的列名,因为您保留了单词。

Click here for SQL Fiddle

介绍您的新朋友 myview

cREATE VIEW myview AS 
SELECT wkday, '9-10'  AS rng, `9-10`  AS cd from `mytable` 
UNION  
SELECT wkday, '10-11' AS rng, `10-11` AS cd from `mytable` 
UNION 
SELECT wkday, '11-12' AS rng, `11-12` AS cd from `mytable` 
UNION 
SELECT wkday, '12-1'  AS rng, `12-1`  AS cd from `mytable` 
UNION 
SELECT wkday, '1-2'   AS rng, `1-2`   AS cd from `mytable` 
UNION 
SELECT wkday, '2-3'   AS rng, `2-3`   AS cd from `mytable` 
UNION 
SELECT wkday, '3-4'   AS rng, `3-4`   AS cd from `mytable`  
;

这是针对您的数据库的一次性查询。

您的观看数据是:

SELECT * FROM myview

wkday           rng     cd
----------------------
Monday      9-10    DA6210
Tuesday     9-10    DA6210
Wednesday   9-10    IA6010
Thursday    9-10    IA6010
Friday      9-10    IA6010
Saturday    9-10    DA6210
Monday      10-11   DA6220
Tuesday     10-11   DA6010
Wednesday   10-11   DA6220
...

创建视图后,您的原始查询编写起来会更简单:

它变成了这个:

SELEct rng FROM myview WHERE wkday='Thursday' AND cd='DA6220';

不再需要OR,无需无休止地重复您正在寻找的代码

...如果你想搜索多个代码,它也是花生:

SELEct rng FROM myview WHERE wkday='Thursday' AND cd IN ('DA6220','IA6010');

但是你的新观点很酷,你可以简单地问:

我的代码是什么日期或范围&#39; DA6220&#39; ?

<强>天

  SELEct wkday FROM myview WHERE cd='DA6220';

结果:

wkday
----------
Tuesday
Wednesday
Monday

范围

  SELEct rng FROM myview WHERE cd='DA6220';

结果:

rng
-----
11-12
10-11
10-11

这是VIEW的典型应用。它让你的生活更轻松。

答案 2 :(得分:0)

阐述我的评论:

SELECT *
  FROM `table`
 WHERE 0 < LOCATE("DA6220", CONCAT(
          `9-10`, " ", `10-11`, " ", `11-12`, " ",
          `12-1`, " ", `1-2`, " ", `2-3`, " ", `3-4`
       ))

这种方法的好处在于您不必重复重复搜索字符串。它可能稍微OR版本慢。