MySql IN子句使用变量

时间:2016-03-18 13:57:39

标签: mysql sql

我有一个名为product的表,其中包含idname列。 我想使用多个名称搜索产品。这个列表来自另一个选择,我把它放在一个变量中。

我想要做的是:选择与列表元素具有相同名称的产品的id

-- 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);

编辑: 更多详细信息如下所示。

-- 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);

在这里,我将遍历DataToProcess临时表

的记录
-- 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;

2 个答案:

答案 0 :(得分:2)

您可以使用FIND_IN_SET()

SET @products = 'Chair,Mattresses,Table';

SELECT DISTINCT
    `id`
FROM
    `product`
WHERE
    FIND_IN_SET(`name`, @products);

其他选项是使用REGEXP()

SET @products = 'Chair,Mattresses,Table';
SET @products = REPLACE(@products,",","|");

SELECT DISTINCT
    `id`
FROM
    `product`
WHERE
    `name` REGEXP @products

答案 1 :(得分:0)

你可以把它放在一个SELECT中,如果这当然是一个选项..

SELECT DISTINCT
   id 
FROM 
   product p
WHERE 
   p.name IN (SELECT include_names FROM include_this) 

或使用FIND_IN_SET功能