简体   繁体   English

如何从联结表中检索值作为字符串?

[英]How to retrieve values from junction table as a String?

I have 3 tables in MYSQL, VideoCategory is the junction table between Video and category 我在MYSQL中有3个表,VideoCategory是Video和category之间的连接表

Video
Category
VideoCategory

it means: each video can bleong to many categories (VideoCategory) table. 这意味着:每个视频都可以归类到许多类别(VideoCategory)表。

My goal is to retrieve a "SMART" way of these values: it means: Video, Comma Delimied String of Categories 我的目标是检索这些值的“ SMART”方式:这意味着:视频,逗号分隔的类别字符串

ex: 例如:

"video1", "1, 2, 3"
"video2", "1, 4"
"video"3", ""

(video 3 has no categories assigned) (视频3未分配类别)

Any idea on how to do that without using mysql loops ? 任何不使用mysql循环怎么做的想法?

group_concat and a couple of join s should do the trick: group_concat和几个join可以解决问题:

SELECT video.name, 
       GROUP_CONCAT(category.name ORDER BY category.name SEPARATOR ', ')
FROM   video v
JOIN   videocategory vc ON v.id = videocategory.video_id
JOIN   category c ON videocategory.category_id = c.id

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

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