簡體   English   中英

將MySQL子查詢轉換為JOIN查詢

[英]Convert MySQL subquery to JOIN query

我正在嘗試從下面的表結構中獲取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`);

但是這里的問題是,標記表中的每個引號可能有多個條目,我想以逗號分隔的格式檢索它。

到目前為止,這是我嘗試過的

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` 

但是我不想使用子查詢來完成該任務。

請在不使用子查詢的情況下幫助我構建此查詢。

    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