开发者

How to use the 'like' operator in SQL?

I want to selec开发者_运维知识库t from C_Table where Name='John' and use the like operator. For example,

select Name from C_Table where Name='John' AND where Details like %Boy%

How do I do this?

(Table name is C_Table)
-----------------------------------------------
Name   |  P_No  |  C_No   |  Details          |
-----------------------------------------------
John   |  001   |  001    |  Good Boy         |
John   |  002   |  002    |  Naughty Boy      |
John   |  003   |  003    |  Very Bad Boy     |
Mary   |  004   |  004    |  Beautiful Girl   |
Mary   |  005   |  005    |  Pretty Girl      |
Mary   |  006   |  005    |  Gorgeous         |
-----------------------------------------------


You almost had it:

select name from table where name="John" and details like '%Boy%';


What you said works, except only one WHERE is used and %Boy% needs to be wrapped in single quotes too:

SELECT Name FROM C_Table WHERE Name = 'John' AND Details LIKE '%Boy%'


Very close - the WHERE keyword is only used once in a SQL statement, and you control the filtration (called predicates) using AND, OR. Combinations of the AND/OR can be given precedence using matching brackets-- "(" and ")".

SELECT Name 
  FROM C_Table 
 WHERE Name LIKE 'John' 
   AND Details LIKE '%Boy%'

Something to be aware of when using wildcarding in a LIKE expression is - when an index exists on a column such as C_TABLE.name, if you wildcard the left side-- name LIKE '%John'-- the index can not be used. This means the query isn't as fast as it could be. Wildcarding the right side--name LIKE 'John%' doesn't have this problem. Try not to use leftside wildcarding, if you don't have to.


SELECT Name
FROM C_Table
WHERE Name = 'John'
  AND Details LIKE '%Boy%'

This will return all rows where the Name column is 'John' and the Details column contains "Boy" (the % is a wildcard, so it'll match anything that has the word Boy with anything before and after it).

You only need to specify WHERE once, ANDs and ORs after that point will extend the WHERE clause. Also, parameters need to be quoted when they are strings.


SELECT Name FROM C_Table WHERE Name='John' AND Details LIKE '%Boy%'


You were close, try this

select * 
from C_Table
where Name='John' 
AND Details like '%Boy%'


select Name from C_Table where Name='John' and Details like '%Boy%'


try this:

SELECT Name FROM C_Table WHERE Name='John' AND Details like '%Boy%'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜