mysql in select 子句_mysql where in子句与in子句后的select语句

bd96500e110b49cbb3cd949968f18be7.png

I have a varchar field which store values like 2,1 and I am using a query to select the data. The query is this one:

SELECT no

FROM c_head

where id = 9

which give output 2,1

and after that, I use this query

SELECT id, item

FROM c_item

where type_head IN (SELECT no

FROM c_head

where id = 9)

ORDER BY item

and its not working its working like type_head IN (2) instead of type_head IN (2,1)

but when I simply use hard coded its working

SELECT id, item

FROM c_item

where type_head IN (2,1)

ORDER BY item

but its not working with subquery why?

please help me

解决方案

To store comma separated values in column is bad design you should look at Database Normalization and do normalize your structure by storing all related type_head in a junction table,but if you can't change structure so in mysql you can use FIND_IN_SET() and join your c_head table,it will select records if it find the value in provided set,IN() will not work for values in set or in comma separated list

SELECT i.id, i.item

FROM c_item i

JOIN c_head h ON(FIND_IN_SET(i.type_head,h.no) > 0)

WHERE h.id = 9

ORDER BY i.item

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值