Select...在 (column1) 中,其中 column1 为“1,4,7”

Select...in (column1) where column1 is '1,4,7'

我需要执行 'where in(X)' 搜索,其中 X 的值是 table.

中逗号分隔的值列表

Table-1:

itemId   colors(nvarchar)
 1          1, 3
 2          2

Table-2:

colorId colorName
   1      Red
   2      Yellow
   3      Blue

我正在寻找这种输出...

itemId colorName
  1     Red
  1     Blue

我试过了,但我认为内部 Select 需要 return 多行才能正常工作,而不是值是逗号分隔值的单行。

select itemId, colorName 
from Table1 t1
left join Table2 t2 on t2.colorId in (select colors from Table1 where itemId = 1)
where itemId = 1;

你可以使用 find_in_set

select itemId, colorName 
from Table1 t1
left join Table2 t2 on  find_in_set(t2.colorId , t1.colors) > 0
where itemId = 1;

http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set

以规范化的名义,你真的应该把 table1 变成

itemid | colorid
-------+--------
     1 |       1
     1 |       3
     2 |       2

不仅那些逗号分隔的字段更新起来很烦人,而且 find_in_set 是我尽可能避免使用的功能之一。 (因为实际上你是在字符串中搜索一个数字,这通常意味着搜索一个字符串,这比仅使用建议的 table 并添加有用的索引效率低)

无论如何,如果您更改 table_1,查询将是:

SELECT t1.itemid, t2.colorname
FROM table1 t1
LEFT JOIN table2 t2 USING (colorid)
WHERE t1.itemid=1
ORDER BY t1.itemid

如果您需要颜色名称列表:

SELECT t1.itemid, GROUP_CONCAT(t2.colorname)
FROM table1 t1
LEFT JOIN table2 t2 USING (colorid)
WHERE ...
GROUP BY t1.itemid

这将 return 元组 (1,"Red,Blue") 和 (2,"Yellow").

(与 GROUP_CONCAT(t2.colorid) 类似)