将多个SQL语句合并为一个

时间:2018-08-18 12:04:15

标签: mysql sql

如何将这些语句合并到一个SQL语句中?

select city from station where city like 'a%';

select city from station where city like 'e%';

select city from station where city like 'i%';

select city from station where city like 'o%';

select city from station where city like 'u%'; 

3 个答案:

答案 0 :(得分:5)

显而易见的方法是union all

select city from station where city like 'a%' union all
select city from station where city like 'e%' union all
. . . 

也许几乎是显而易见的:

where city like 'a%' or city like 'e%' or . . . 

您还可以使用其他方法,例如:

where left(city, 1) in ('a', 'e', 'i', 'o', 'u')

(注意:并非所有数据库都支持left()。)

更典型的方法是某种形式的正则表达式,但是语法取决于数据库。

答案 1 :(得分:1)

where SUBSTR(city,1,1) in ('a', 'e', 'i', 'o', 'u')或使用left(city, 1)(如果数据库支持)。

您始终可以在语句之间使用union / union alllike 'a%' or like 'e%' ....,但在这种情况下我更喜欢使用substrleft

答案 2 :(得分:0)

恕我直言,最好的方法(也将利用现有索引)将是使用OR:

select city from station 
where 
  city like 'a%' OR 
  city like 'e%' OR
  city like 'i%' OR
  city like 'o%' OR
  city like 'u%';

注意:在MS SQL Server和postgreSQL中,这会生成最佳执行计划。

相关问题