I have a table called product with id
and name
columns.
I want to search for product using multiple names. This list is coming from another select and I put it in a variable.
What I want to do is: SELECT the id
of product that has the same name with the list elements.
-- works but I have my values in a variable.
select distinct id from product where name IN ('Chair','Mattresses','Table');
-- doesn't work - THIS IS WHAT I WANT
set @products = 'Chair,Mattresses,Table';
select distinct id from product where name IN (SELECT CONCAT("'", REPLACE(@products, ",", "','"), "'"));
-- doesn't work -- THIS IS ANOTHER ALTERNANATIVE FOR ME BUT IT DOESN'T WORK
set @products = 'Chair,Mattresses,Table';
set @commaSeparated = (SELECT CONCAT("'", REPLACE(@products, ",", "','"), "'"));
select distinct id from product where name IN (@commaSeparated);
EDIT: More detail information is presented below.
-- Temporary table to store the data from the FIRST query
CREATE TEMPORARY TABLE DataToProcess (
productNames TEXT NOT NULL,
locations TEXT NOT NULL
) CHARACTER SET utf8 COLLATE utf8_general_ci;
-- Read data and store in Temporary table
INSERT INTO DataToProcess
SELECT
REPLACE(REPLACE(names, '\r\n', ','), "'", "\'") AS productNames,
REPLACE(REPLACE(locations, '\r\n', ','), "'", "\'") AS locations
FROM table1
LEFT JOIN table2 USING (id)
WHERE table1.startDate <= NOW()
AND table2.endDate > DATE_ADD(NOW(), INTERVAL 15 MINUTE);
Here, I will iterate through the records of DataToProcess
temporary table
-- Define curser_finished
DECLARE product_cursor_finished INTEGER DEFAULT 0;
-- declare cursor for DataToProcess
DECLARE product_cursor CURSOR FOR SELECT * FROM DataToProcess;
-- declare NOT FOUND handler for product_cursor
DECLARE CONTINUE HANDLER FOR NOT FOUND SET product_cursor_finished = 1;
OPEN product_cursor;
get_productsAndLocations: LOOP
FETCH product_cursor INTO products, locations;
**** THIS IS WHERE I WANT TO USE `SELECT WHERE IN`
END LOOP get_ProductsAndLocations;
CLOSE product_cursor;