简体   繁体   English

如何在SQL查询中检查子字符串?

[英]How do I check the substring in a query in SQL?

Here is my Weapons table: 这是我的Weapons表:

Name / DPS / Style

Noxious Bow / 1000 / Range
Chaotic Staff / 800 / Magic
Armadyl Crossbow / 750 / Range
Saradomin Godsword / 600 / Melee
Dragon Battlestaff / 600 / Magic
Dragon Longsword / 550 / Melee
Elder Shortbow / 500 / Range
Darklight / 400 / Melee

Here is what I tried: 这是我尝试过的:

SELECT Name, DPS, Style
FROM Weapons
HAVING SUBSTRING(Name, 1, 1)='D';

I want all Weapons that start with the letter D to be displayed. 我希望显示所有以字母D开头的Weapons However, this code is giving me a syntax error. 但是,这段代码给了我一个语法错误。

Try this: 尝试这个:

SELECT Name, DPS, Style
FROM Weapons
WHERE Name LIKE 'D%';

As you're using Oracle, the function is SUBSTR , not SUBSTRING , and for any RDBMS, you'd need to use WHERE , not HAVING : 在使用Oracle时,该函数是SUBSTR ,而不是SUBSTRING ,对于任何RDBMS,您需要使用WHERE ,而不是HAVING

SELECT Name, DPS, Style
FROM Weapons
WHERE SUBSTR(Name, 1, 1)='D';

SUBSTRING would have worked fine in Microsoft SQL Server. SUBSTRING在Microsoft SQL Server中可以正常工作。

Also, the LEFT function is quite widely supported, and might stand a better chance of using an index, if one is defined on Name . 另外, LEFT函数得到了广泛的支持,如果在Name上定义了索引,则使用索引的机会会更大。 This will work in Oracle, SQL Server and others: 这将在Oracle,SQL Server和其他服务器中运行:

SELECT Name, DPS, Style
FROM Weapons
WHERE LEFT(Name, 1)='D';

However, the best option is probably using LIKE, which is widely-supported and flexible, and will also likely use an index on the Name column, if one exists, as long as the fixed text you're searching for is at the beginning: 但是,最好的选择可能是使用LIKE,LIKE被广泛支持并且很灵活,并且只要您要搜索的固定文本在开头,就可能会在Name列上使用索引(如果存在)。

SELECT Name, DPS, Style
FROM Weapons
WHERE Name LIKE 'D%';

You could probably do with going through a basic SQL tutorial at this stage, and bear in mind that while "SQL" has a standard core, each version is different and you'll need to look for Oracle-specific advice if you're using Oracle. 您可能需要在此阶段阅读基本的SQL教程,并且请记住,尽管“ SQL”具有标准核心,但是每个版本都不相同,如果您使用的是Oracle,则需要寻求针对Oracle的建议甲骨文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM