1

How should I write a query using the LIKE operator checking for multiple values.

Something similar to LIKE ('car%','bus%')

enter image description here enter image description here

output I want:

car            373
Bus            2
Heavy Vehicle  3
Motor Cycle    79

As you can see from the desired output above, I need to subtotal each car, Bus, Heavy Vehicle, etc.

1

3 Answers 3

6

Switch to REGEXP:

WHERE vehicletype REGEXP '^(car|bus)'
2

You can define a derived table with your patterns, example:

select v.* 
from vehicle v 
join ( select 'Car%' as s union all select 'Bus%' ) as p 
    on v.vehicletype like p.s;

alternatively use a temp table:

create temporary table patterns (p varchar(20) not null);
insert into patterns (p) values ('Car%'),('Bus%');
select v.* 
from vehicle v 
join patterns as p 
    on v.vehicletype like p.p;

Edit: aggregate volume, group by pattern

select substr(p.p,1,length(p.p)-1), sum(volume) 
from vehicle v 
join patterns as p 
    on v.vehicletype like p.p 
group by substr(p.p,1,length(p.p)-1);
4
  • Only one table with the datas of Vehicle Type and amount that s combination of car1,car2,car3,bus1,bus2...etc need to sum of volume Like 'Car%' and LIke 'Bus%'
    – dita
    Commented Jun 26, 2018 at 14:18
  • Not sure what you are asking, but I added an example. Commented Jun 27, 2018 at 6:32
  • I am doing a task in which it is required to find the first day and last day of the year by given input as a year.
    – dita
    Commented Jun 27, 2018 at 8:12
  • 1
    I think you need to update your question. It is not clear what you are asking, there is not even a date in your question. Add CREATE TABLE and INSERT statements with sample data that illustrates what you are trying to do. Commented Jun 27, 2018 at 8:17
0

You can simply use the OR in your MySQL query. For example

SELECT * FROM `tableName` WHERE vehicletype LIKE '%val1%' OR vehicletype LIKE '%val2%' 
2
  • If you look at the author's result set, then you might notice that there are other requirements besides the simple request to search for multiple values.
    – John K. N.
    Commented Jun 26, 2018 at 9:45
  • this answer helped me for another trouble so I voted + because it helped me to solve my problem (not this one of the thread). So thank you
    – P.Davide
    Commented Sep 24, 2023 at 13:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.