简体   繁体   English

子查询在哪里无法正常工作

[英]WHERE IN with subquery NOT WORKING as expected

I am trying to get result from my categories table using the parent path i have created. 我正在尝试使用创建的父路径从类别表中获取结果。 When i launch the request WHERE IN with manual data it's working perfectly. 当我使用手动数据启动请求WHERE IN时,它运行良好。 When i am trying the same request dynamically with subquery, i got only one result instead of 4 expected. 当我使用子查询动态尝试相同的请求时,我只有一个结果,而不是预期的4。 I do not understand why, can you help me ? 我不明白为什么,你能帮我吗?

http://sqlfiddle.com/#!2/88b68/6 http://sqlfiddle.com/#!2/88b68/6

/*Working query*/
SELECT t.id_categorie FROM t 
WHERE t.id_categorie IN (1396,1399,1403,1412)

/*Not working by subquery ??*/
SELECT cat.id_categorie FROM t as cat
WHERE 
cat.id_categorie IN (SELECT REPLACE(t.path,'.',',') FROM t WHERE t.id_categorie = 1412)

Thanks by advance, 预先感谢,

Regards, 问候,

Using in with a comma delimited list does not do what you want. 用逗号分隔列表使用in并不能满足您的要求。 Even when you use a subquery. 即使您使用子查询。 You could try this: 您可以尝试以下方法:

SELECT cat.id_categorie
FROM t cat
WHERE EXISTS (SELECT 1
              FROM t
              WHERE t.id_categorie = 1412 AND
                    find_in_set(cat.id_categorie, REPLACE(t.path, '.', ',')) > 0
             );

I'm not sure what your data looks like or even what this query is supposed to be doing (it seems strange that the subquery is on the same table as the outer query). 我不确定您的数据是什么样子,甚至不确定此查询应该做什么(子查询与外部查询位于同一表上似乎很奇怪)。 Usually, though, you want to store things in tables rather than delimited lists. 但是,通常,您希望将内容存储在表中,而不是定界列表中。 You see, SQL has a built-in data structure for lists. 您会看到,SQL具有用于列表的内置数据结构。 It is called a table. 它称为表格。

The reason this does not work is that your inner SELECT produces a single comma-separated VARCHAR , rather than four individual integers. 这不起作用的原因是您的内部SELECT生成了一个逗号分隔的VARCHAR ,而不是四个单独的整数。

In MySQL you can use find_in_set , like this: 在MySQL中,您可以使用find_in_set ,如下所示:

SELECT cat.id_categorie FROM t as cat
WHERE find_in_set(cat.id_categorie, (
  SELECT REPLACE(t.path,'.',',')
  FROM t WHERE t.id_categorie = 1412))

What I did was replacing the IN expression in your query with a call to find_in_set , leaving everything else the same. 我所做的是用对find_in_set的调用替换了查询中的IN表达式,其他所有内容均保持不变。

Demo 演示版

However, this solution is fundamentally flawed, because it stores multiple values in a single column to represent a many-to-many relationship. 但是,该解决方案从根本上来说是有缺陷的,因为它在单个列中存储了多个值以表示多对多关系。 A better approach to implementing this requirement is using a separate table that connects rows of the table to their related rows. 实现此要求的更好方法是使用单独的表,该表将表中的行连接到其相关行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM