简体   繁体   English

SQL帮助〜关系数据库模型〜显示结果

[英]SQL Help ~ Relational Database Model ~ Displaying Results

Currently I have a database with about 10 tables. 目前我有一个包含大约10个表的数据库。 I have successfully joined them all together using inner joins and have displayed the results. 我已经使用内部联接成功地将它们连接在一起并显示了结果。

However, I am having trouble where one column could have multiple values attributed to it. 但是,我遇到一个列可能有多个值归因于它的问题。

For example, my database has this loaded into it: 例如,我的数据库已加载到其中:

item    id
item1 | 1
item2 | 1
item2 | 2
item2 | 3

I joined it like this: 我这样加入:

SELECT Main.item, thing.id FROM Main INNER JOIN thing ON Main.MainID = thing.id

I would like to concatenate the three instances of 'id' together for item2, without displaying 'item2' three times on my results page. 我想在item2中连接'id'的三个实例,而不是在我的结果页面上三次显示'item2'。 A delimiter between 'id's might be '&', where the result would be: 'id'之间的分隔符可能是'&',结果如下:

"item1" "1"
"item2" "1 & 2 & 3"

I am pretty sure my problem is in my inadequate use of SQL but I am also using Javascript, PHP, & HTML to display the results so please let me know if you think that might be where the problem is. 我很确定我的问题在于我对SQL的使用不足,但我也使用Javascript,PHP和HTML来显示结果,所以如果您认为可能存在问题,请告诉我。

Thanks 谢谢

Just group by your item and use GROUP_CONCAT as aggregate on your ids: 只需按项目分组,并在您的ID上使用GROUP_CONCAT作为聚合:

SELECT items.item, GROUP_CONCAT(ids.id SEPARATOR ' & ')
FROM items
JOIN ids ON items.id=ids.id
GROUP BY items.item

See MySQL GROUP_CONCAT function for more information. 有关更多信息,请参阅MySQL GROUP_CONCAT函数。

If you are using MySQL you can create groups (GROUP BY) and then you can use the GROUP_CONCAT MySQL function. 如果您使用MySQL,您可以创建组(GROUP BY),然后您可以使用GROUP_CONCAT MySQL函数。

MSSQL "GROUP_CONCAT" MSSQL“GROUP_CONCAT”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM