在MySQL中为此使用LOCATE()和SUBSTRING()方法。让我们首先创建一个表-
create table DemoTable -> ( -> Title text -> );
使用插入命令在表中插入一些记录-
insert into DemoTable values('Introduction To Java'); insert into DemoTable values('Introduction - To MySQL');
使用select语句显示表中的所有记录-
select *from DemoTable;
输出结果
这将产生以下输出-
+-------------------------+ | Title | +-------------------------+ | Introduction To Java | | Introduction - To MySQL | +-------------------------+ 2 rows in set (0.00 sec)
以下是在子字符串中的特殊字符之前显示子字符串的查询-
select distinct -> if(LOCATE(' - ',Title)>0, SUBSTRING(Title, 1, LOCATE(' - ', Title)), Title) from DemoTable;
输出结果
这将产生以下输出-
+-----------------------------------------------------------------------------+ | if(LOCATE(' - ',Title)>0, SUBSTRING(Title, 1, LOCATE(' - ', Title)), Title) | +-----------------------------------------------------------------------------+ | Introduction To Java | | Introduction | +-----------------------------------------------------------------------------+ 2 rows in set (0.00 sec)