将MySQL子查询转换为JOIN查询

时间:2015-12-12 05:08:24

标签: mysql

我正在尝试从下表结构中获取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`);

但问题是,每个引号的tags表中可以有多个条目,我想以逗号分隔格式检索它。

这是我到目前为止所尝试的,

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` 

但我不想使用子查询来完成这项工作。

请在不使用子查询的情况下帮助我构建此查询。

1 个答案:

答案 0 :(得分:0)

    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`