Home > other >  mysql query to filter LIKE combined with IN
mysql query to filter LIKE combined with IN

Time:01-29

CREATE TABLE IF NOT EXISTS botPatterns (
  `boltP` varchar(200) NOT NULL
)  ;

INSERT INTO `botPatterns` (`boltP`) VALUES
  ('6X135/6X139.7'),
  ('8X165.1'),
  ('8X165.1/8X170' ),
  ('8X170' );


CREATE TABLE IF NOT EXISTS Vehicles (
  `Brand` varchar(200) NOT NULL,
  `Pattern` varchar(200) NOT NULL
)  ;

INSERT INTO `Vehicles` (`Brand`,`Pattern`) VALUES
  ('Audi','6X135'),
  ('Audi','8X165.1'),
  ('BMW','8X170' ),
  ('Ford','9X139.7' );

What I need here is to get all Vehicles for which i have boltPatterns.

Example 1. Audi 8x165.1 was contained in table botPatterns

Example 2. For is 9x139.7 was also contained in table botPatterns but under value 6X135/6X139.7

One of the approaches would be

select * from vehicles
where pattern in 
(
    select boltp from botpatterns
)

But this will return only exact match.

My output here should return all results from table Vehicles beside Ford.

Fiddle : enter image description here

CodePudding user response:

Dirty

SELECT *
FROM botPatterns
JOIN Vehicles ON LOCATE(Vehicles.Pattern, botPatterns.boltP)
boltP Brand Pattern
6X135/6X139.7 Audi 6X135
8X165.1/8X170 Audi 8X165.1
8X165.1 Audi 8X165.1
8X170 BMW 8X170
8X165.1/8X170 BMW 8X170

More accurate

SELECT *
FROM botPatterns
JOIN Vehicles ON FIND_IN_SET(Vehicles.Pattern, REPLACE(botPatterns.boltP, '/', ','))
boltP Brand Pattern
6X135/6X139.7 Audi 6X135
8X165.1/8X170 Audi 8X165.1
8X165.1 Audi 8X165.1
8X170 BMW 8X170
8X165.1/8X170 BMW 8X170

fiddle

If you need in brands list only then use SELECT DISTINCT Vehicles.Brand ...

  • Related