2015-12-12 50 views
2

我想從下面的表結構的quotes.quote,authors.author和tags.tag,轉換MySQL的子查詢加入查詢

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` 

但我不希望使用子查詢弄完。

請幫我建立這個查詢,而不使用子查詢。

+0

爲什麼你阻止使用*子查詢*?以及..你上面提供的查詢是否適合你? – RubahMalam

+0

@RubahMalam只是爲了提高性能。不會比較快地加入? – Stranger

+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`