问题描述
我四处寻找,一无所获.
I have searched around and came up with nothing.
我有 2 个表,不必为每篇显示我需要以某种方式加入它们的帖子查询数据库.
I have 2 tables and to not have to query the database for every post that shows i need to join them somehow.
我想从具有 post 表中 pics
字段的 id 的 pics 表中获取 url
.现在我的问题是:pics
字段是一个逗号分隔的列表"(4,1 或 32,4,32,2),因为每个帖子通常有不止一张图片.
I want to get the url
from the pics table that have the id of the pics
field in posts table. Now heres my problem: the pics
field is a commma separated "list" (4,1 or 32,4,32,2), because every post usually have more than one picture.
表设置:
帖子:
图片:
推荐答案
我强烈建议您修复当前的数据库结构,以免将数据存储在逗号分隔的列表中.您应该按照如下方式构建表格:
I strongly advise that you fix your current database structure so you are not storing the data in a comma separated list. You should structure your tables similar to the following:
然后您可以通过加入表格轻松获得结果:
Then you can easily get a result by joining the tables:
参见 SQL Fiddle 和演示.
如果你不能改变你的表,那么你应该能够使用FIND_IN_SET
进行查询:
If you cannot alter your table, then you should be able to query using FIND_IN_SET
:
参见SQL Fiddle with Demo.
编辑,如果您希望数据显示为逗号分隔的列表,那么您可以使用GROUP_CONCAT
.
Edit, if you want the data displayed as a comma-separated list then you can use GROUP_CONCAT
.
查询 1:
参见SQL Fiddle with Demo
查询 2:
参见SQL Fiddle with Demo
这篇关于MYSQL 连接逗号分隔查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!