如何正确使用 IN 子句从 MySQL 中的另一列获取值?

How to use properly IN clause getting the value from another column in MySQL?

在一个 table 中,我有一个城市列表,在另一个中有一个客户列表。在客户端上,我有一个 varchar 列,用于标识以逗号分隔的城市列表(例如:“2,3,4”)。

当我尝试列出客户的城市时,它只显示列表的第一个城市。 似乎在值上添加了一些引号,例如:

select GROUP_CONCAT(city.name) 来自 city.id_city in ('2,3,4')

的城市

¿如何避免这种情况?

https://dbfiddle.uk/?rdbms=mysql_5.6&fiddle=a70c667e820c3208053b324075b0462c

CREATE TABLE `city` (
  `id_city` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id_city`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `client` (
  `id_client` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  `cities` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id_client`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO city (id_city,name) VALUES ('1','New York');
INSERT INTO city (id_city,name) VALUES ('2','Boston');
INSERT INTO city (id_city,name) VALUES ('3','San Diego');
INSERT INTO city (id_city,name) VALUES ('4','Seatle');
INSERT INTO city (id_city,name) VALUES ('5','Chicago');

INSERT INTO client (id_client,name,cities) VALUES ('1','Client_1','2,3,4');

select client.id_client, client.name, (select GROUP_CONCAT(city.name) 
from city where city.id_city in (client.cities)) as cities from client;

您不能直接将列表传递给您的查询。您需要将代码更改为 -

SELECT client.id_client,
       client.name,
       (SELECT GROUP_CONCAT(city.name) 
          FROM city
         WHERE FIND_IN_SET(city.id_city, client.cities) <> 0) AS cities
  FROM client;

DB Fiddle.

虽然这解决了您的目的,但我认为您必须考虑访问 this link,它清楚地表明存储逗号分隔值确实是一个非常糟糕的主意。