2012-09-22 163 views
1

我試圖讓所有的線程標記名稱「測試」,例如,以及所有其他標記。如果我添加一個where子句到我的INNER JOIN選擇,那麼它將獲得具有該標記的線程,但它不會獲得該線程的其餘標記(每個標記都是一個單獨的行,我使用組concat來組合它們)。我怎樣才能得到剩餘的標籤呢?選擇所有包含標籤和其他標籤的主題?

我有以下SQL

SELECT `threads`.`id`, 
     `threads`.`title` AS `title`, 
     `threads`.`created_at` AS `created_at`, 
     `threads`.`views` AS `views`, 
     `threads`.`comments` AS `comments`, 
     `threads`.`user_id` AS `user_id`, 
     `tags` 
FROM `threads` 
INNER JOIN 
    (SELECT threads_id, 
      GROUP_CONCAT(DISTINCT `thread_tags`.`thread_tags_title`) AS tags 
    FROM `thread_tags` 
    WHERE `thread_tags`.`thread_tags_title` = 'test' 
    GROUP BY threads_id) thread_tags ON `threads`.`id` = `thread_tags`.`threads_id` 
WHERE `threads`.`status` = '1' 
ORDER BY `threads`.`views` DESC, `threads`.`created_at` DESC LIMIT 25 
OFFSET 0 

而下面的方案

標籤

CREATE TABLE `tags` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `title` varchar(200) NOT NULL, 
    `status` int(11) NOT NULL, 
    `created_at` datetime NOT NULL, 
    `updated_at` datetime NOT NULL, 
    `description` varchar(255) DEFAULT NULL, 
    `doctors` int(11) DEFAULT NULL, 
    `threads` int(11) DEFAULT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; 

的主題標籤(表線程ID和標籤ID)

CREATE TABLE `thread_tags` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `threads_id` int(11) NOT NULL, 
    `tag_id` int(11) NOT NULL, 
    `thread_tags_title` varchar(255) NOT NULL DEFAULT '', 
    `created_at` datetime NOT NULL, 
    `updated_at` datetime NOT NULL, 
    `description` varchar(255) DEFAULT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; 

主題

CREATE TABLE `threads` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `user_id` int(11) NOT NULL, 
    `title` varchar(200) NOT NULL, 
    `body` text NOT NULL, 
    `status` int(11) NOT NULL, 
    `views` int(11) NOT NULL, 
    `rating` int(11) NOT NULL, 
    `comments` int(11) NOT NULL, 
    `created_at` datetime NOT NULL, 
    `updated_at` datetime NOT NULL, 
    `metadata` text, 
    PRIMARY KEY (`id`), 
    KEY `title` (`title`) 
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1; 
+0

添加where子句,有一噸的SELECT語句(它的工作,但它不是我想要的,也不是有效的),做了兩隻選擇一個得到所有數組中的線程,然後是另一個在數組中選擇的線程,但這也不是我想要的。如果可能,我想保留在單個查詢中。 – Steven

回答

1

喜歡的東西

SELECT threads.*, GROUP_CONCAT(tags.title) 
FROM threads AS t 
LEFT JOIN thread_tags AS tt ON t.id = tt.threads_id 
LEFT JOIN tags AS tt ON tt.tag_id = tags.id 
WHERE t.id IN (
    SELECT tt.threads_id 
    FROM thread_tags AS tt 
    JOIN tags ON tt.tag_id = tags.id 
      AND tags.title = "test" 
) 
GROUP BY t.id