简体   繁体   English

带有2个表的MYSQL类搜索

[英]MYSQL Like search with 2 Tables

i have the following problem. 我有以下问题。 A video have multiple tags like high definition, 720p, 1080p and so on each tag has its own record. 视频具有多个标签,例如高清,720p,1080p等,每个标签都有自己的记录。 All tags are in own table its named tags. 所有标签都在自己的表中其命名标签。

Here are the sample table tag. 这是样本表标签。

CREATE TABLE IF NOT EXISTS `tag` (
  `video_tag_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `video_id` bigint(20) DEFAULT NULL,
  `tag_name` varchar(300) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `tag_count` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`video_tag_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

So when i use a like search from another table to this it shows me for each tag the same video. 因此,当我从另一张表进行类似搜索时,它会为每个标签显示相同的视频。

How i could make this ? 我怎么能做到这一点?

We assume you mean table where you refer to database . 我们假设您是指引用数据库的

You will need to substitute your correct table structure for the videos table: 您将需要用正确的表结构替换视频表:

SELECT 
  videos.video_id,
  videos.name,
  tag.tag_name
FROM videos JOIN tag ON videos.video_id = tag.video_id
WHERE videos.name LIKE '%the name of your video%'

The above will list one row for each tag the video has. 上面将为视频中的每个标签列出一行。

To return a list of tags in one row, use GROUP_CONCAT() : 要返回一行标签列表,请使用GROUP_CONCAT()

SELECT 
  videos.video_id,
  videos.name,
  GROUP_CONCAT(tag.tag_name) AS tags
FROM videos JOIN tag ON videos.video_id = tag.video_id
WHERE videos.name LIKE '%the name of your video%'
GROUP BY videos.video_id, videos.video_name

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

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