SQL第3课:具有约束的查询(第2部分)

当编写WHERE带有包含文本数据的列的子句时,SQL支持许多有用的运算符来执行诸如不区分大小写的字符串比较和通配符模式匹配之类的操作。我们在下面显示一些常见的文本数据特定运算符:

 Operator Condition  Example 
 =  区分大小写的精确字符串比较(注意单个等于  col_name= ''abc''
 != or <>  区分大小写的精确字符串不等式比较  col_name != "abcd"
 LIKE  不区分大小写的精确字符串比较  col_name LIKE "ABC"
 NOT LIKE  不区分大小写的精确字符串不等式比较  col_name NOT LIKE "ABCD"
 %  在字符串中的任意位置使用以匹配零个或多个字符的序列(仅适用于LIKE或NOT LIKE)  

col_name LIKE "%AT%"
(matches "AT", "ATTIC", "CAT" or even "BATS")

 _  在字符串中的任意位置使用以匹配单个字符(仅适用于LIKE或NOT LIKE)  col_name LIKE "AN_"
(matches "AND", but not "AN")
 IN (…)  字符串存在于列表中  col_name IN ("A", "B", "C")
 NOT IN (…)  列表中不存在字符串  col_name NOT IN ("D", "E", "F")
你知道吗?
必须将所有字符串都用引号引起来,以便查询解析器可以将字符串中的单词与SQL关键字区分开。

练习:

WHERE再次是带有子句的查询的定义,继续尝试使用上述运算符编写一些查询,以将结果限制为我们在以下任务中所需的信息。

选择约束查询
SELECT column, another_column, …
FROM mytable
WHERE condition
    AND/OR another_condition
    AND/OR …;

Table: Movies

Id Title Director Year Length_minutes
1 Toy Story John Lasseter 1995 81
2 A Bug's Life John Lasseter 1998 95
3 Toy Story 2 John Lasseter 1999 93
4 Monsters, Inc. Pete Docter 2001 92
5 Finding Nemo Andrew Stanton 2003 107
6 The Incredibles Brad Bird 2004 116
7 Cars John Lasseter 2006 117
8 Ratatouille Brad Bird 2007 115
9 WALL-E Andrew Stanton 2008 104
10 Up Pete Docter 2009 101
11 Toy Story 3 Lee Unkrich 2010 103
12 Cars 2 John Lasseter 2011 120
13 Brave Brenda Chapman 2012 102
14 Monsters University Dan Scanlon 2013 110
87 WALL-G Brenda Chapman 2042 97

要求:

  1. Find all the Toy Story movies
  2. Find all the movies directed by John Lasseter
  3. Find all the movies (and director) not directed by John Lasseter
  4. Find all the WALL-* movies

答案:

  1.select * from movies where title like "Toy Story%";

  2.select * from movies where director="John Lasseter";

  3.select * from movies where director not like "John Lasseter";

  4.select * from movies where title like "wall-_"

  

原文地址:https://www.cnblogs.com/ljwpython/p/14425761.html