1、问题是这样的,有一个表中的一个字段里面存了多个用户ID,用逗号隔开了,我要把这列的值查出来,每个用户ID分别作为一个条件关联查询。

2、我要查询的账户流水表里面in这些用户ID,如果要直接这样查是不对的,select * from core_account_tx where uid in (select relation_chain from core_invite where uid=632 ),只能查询到第一个用户ID631.

3、如果想把所有的用户ID的流水都查出来,就要把这个多值列里面的用户ID一个个取出来,那么SQL就需要这样写
select
substring_index(substring_index(a.relation_chain,’,’
,b.help_topic_id+1),’,’,-1)
from
(select relation_chain from core_invite where uid=632) a
join
mysql.help_topic b
on b.help_topic_id < (length(a.relation_chain) -length(replace(a.relation_chain,’,’,’’))+1)
替换了如下图4处地方,其他的不用改。

4、如上之后,就可以把查询结果作为IN条件使用了,可以看到查询了多个用户。
select * from core_account_tx where uid in ( select
substring_index(substring_index(a.relation_chain,’,’
,b.help_topic_id+1),’,’,-1)
from
(select relation_chain from core_invite where uid=632) a
join
mysql.help_topic b
on b.help_topic_id < (length(a.relation_chain) -length(replace(a.relation_chain,’,’,’’))+1)
)

当一个字段值包含多个用逗号分隔的用户ID时,直接在IN条件中使用会导致只查询到第一个ID。解决办法是使用SQL的substring_index和replace函数拆分字段,生成新的查询条件。通过将字段拆分成单个ID,然后将其作为IN条件应用于查询,可以获取所有相关用户的流水记录。
1090

被折叠的 条评论
为什么被折叠?



