MySQL:在表列和 group_concat 中使用逗号分隔的 id
在表中,有一列包含用逗号分隔的 id ex: "159,167"
我想在该表和包含这些 id 的表之间执行相当于联接的操作。
例如:
TableA TableB
id desc id desc tableAids stock
1 test1 1 abc 1,2,3 1
2 test2 2 def 1,2 0
3 test3 3 ghi 3,4 10
4 test4
如何通过查询连接两个表?我探索了函数 group_concat() 但它返回一个我无法放入 IN 子句中的字符串。
我想做的是这样的:
Select a.desc from TableA a
LEFT JOIN TableB b on a.id = b.tableAids
WHERE b.stock > 1
In a table, there is a column that contains ids separated by comas ex: "159,167"
I want to do the equivalent of a join between this table and the table that contains those ids.
ex:
TableA TableB
id desc id desc tableAids stock
1 test1 1 abc 1,2,3 1
2 test2 2 def 1,2 0
3 test3 3 ghi 3,4 10
4 test4
How can I join the two tables with a query? I explored the function group_concat() but it returns a string wich I cannot put in a IN clause.
What I am trying to do is something like this:
Select a.desc from TableA a
LEFT JOIN TableB b on a.id = b.tableAids
WHERE b.stock > 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我对你的问题有一个解决方案,但是:
你应该认真考虑重构以摆脱逗号分隔的 id
该解决方案可以满足您现在的需要,但无法优化(mysql 无法使用索引来加速执行,见下文)
试试这个:
Mysql不能使用索引来连接表,因为连接条件中的列包含在函数中。但是,如果您在 TableB.stock 列上有索引,它可能会有所帮助。
请记住:在列中存储多个值是一个很大的NO-NO,您应该尽快摆脱它。以后会引起很多头痛。
I have a solution for your question, but:
you should seriously consider a refactoring to get rid of the coma separated ids
the solution does what you need right now, but it cannot be optimised (mysql cannot use indexes to speed-up the execution, see below)
Try this:
Mysql cannot use indexes for joining the tables because the columns in the join condition are included in a function. However, if you have an index on TableB.stock column, it might help a little.
Remember: storing multiple values in a column is a big NO-NO and you should get rid of that asap. It will cause many headaches later.