简体   繁体   English

将MySQL子查询转换为JOIN查询

[英]Convert MySQL subquery to JOIN query

I'm trying to get the quotes.quote, authors.author and tags.tag from the following table structure, 我正在尝试从下面的表结构中获取quotes.quote,authors.author和tags.tag,

CREATE TABLE IF NOT EXISTS `authors` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `author` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE IF NOT EXISTS `quotes` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `quote` text COLLATE utf8_unicode_ci NOT NULL,
  `author_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `quotes_author_id_foreign` (`author_id`),
);

CREATE TABLE IF NOT EXISTS `quote_tags` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tag_id` int(10) unsigned NOT NULL,
  `quote_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE IF NOT EXISTS `tags` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tag` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
);

ALTER TABLE `quotes`
  ADD CONSTRAINT `quotes_author_id_foreign` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`);

But here the problem is, there can be multiple entry in the tags table for each quotes and I want to retrieve it in the comma separated format. 但是这里的问题是,标记表中的每个引号可能有多个条目,我想以逗号分隔的格式检索它。

Here is what I have tried so far, 到目前为止,这是我尝试过的

SELECT `quotes`.`id` , `quotes`.`quote` , `authors`.`author` , (
  SELECT GROUP_CONCAT( `tag` )
  FROM tags
  JOIN quote_tags
  WHERE quote_tags.tag_id = tags.id
  AND quote_tags.quote_id = quotes.id
) as tags
FROM `quotes`
INNER JOIN `authors` ON `authors`.`id` = `quotes`.`author_id`
INNER JOIN `topics` 

But I don't want to use sub queries to get that done. 但是我不想使用子查询来完成该任务。

Please help me in building this query without using sub queries. 请在不使用子查询的情况下帮助我构建此查询。

    SELECT `_quotes`.`id` , `_quotes`.`quote` , `_authors`.`author`  
   ,GROUP_CONCAT( `tag` )  
    FROM `_quotes`  
    INNER JOIN `_authors` ON `_authors`.`id` = `_quotes`.`author_id`  
    inner join _tags
    JOIN _quote_tags
    on _quote_tags.tag_id = _tags.id  
    AND _quote_tags.quote_id = _quotes.id  
    INNER JOIN `_topics` group by `_quotes`.`id`,`_tags`.`id`

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

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