Mysql 查询(select 列值)中的字段不起作用
Mysql Query where field in (select column value) not works
我试图在 where 子句的帮助下获取一些值,where 子句的值是同一 table.
中记录的值
例如,
select requestedusers from users where username = 'xyz'
当我运行上面的查询时,它给我的结果像abc,mno,tuv
我在另一个查询中使用了该结果,例如 select data from users where username in (abc,mno,tuv)
,我得到了最终结果。
但是我需要像select data from users where username in (select requestedusers from users where username = 'xyz');
这样在单个查询中获得最终结果。
当我尝试 运行 像这样查询时,它 return 我空集。
修正你的数据结构!不要将以逗号分隔的列表存储在单个列中。 SQL 拥有非常棒的列表数据结构。它被称为 table,而不是 string.
你想要一个路口table;也就是说,table 每个用户和每个请求的用户一行。
就是说,有时我们会被其他人非常、非常、非常糟糕的设计决定所困。在这种情况下,您可以使用 find_in_set()
:
select data
from users u
where exists (select 1
from users u2
where find_in_set(u.username, u2.requestedusers) > 0 and
u2.username = 'xyz'
);
性能会很差。除了修复数据模型之外,几乎没有其他方法可以修复性能。
我试图在 where 子句的帮助下获取一些值,where 子句的值是同一 table.
中记录的值例如,
select requestedusers from users where username = 'xyz'
当我运行上面的查询时,它给我的结果像abc,mno,tuv
我在另一个查询中使用了该结果,例如 select data from users where username in (abc,mno,tuv)
,我得到了最终结果。
但是我需要像select data from users where username in (select requestedusers from users where username = 'xyz');
这样在单个查询中获得最终结果。
当我尝试 运行 像这样查询时,它 return 我空集。
修正你的数据结构!不要将以逗号分隔的列表存储在单个列中。 SQL 拥有非常棒的列表数据结构。它被称为 table,而不是 string.
你想要一个路口table;也就是说,table 每个用户和每个请求的用户一行。
就是说,有时我们会被其他人非常、非常、非常糟糕的设计决定所困。在这种情况下,您可以使用 find_in_set()
:
select data
from users u
where exists (select 1
from users u2
where find_in_set(u.username, u2.requestedusers) > 0 and
u2.username = 'xyz'
);
性能会很差。除了修复数据模型之外,几乎没有其他方法可以修复性能。