【问题标题】:Select all threads with tag & the rest of the tags?选择带有标签和其余标签的所有线程?
【发布时间】:2012-09-22 22:23:42
【问题描述】:

例如,我正在尝试获取标签名称为“test”的所有线程以及所有其他标签。如果我在我的 INNER JOIN 选择中添加 where 子句,那么它会获取带有该标签的线程,但它不会获取该线程的剩余标签(每个标签都是单独的行,我使用组 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;

【问题讨论】:

  • 添加一个 where 子句,有大量的 select 语句(这确实有效,但它不是我想要的,也不是有效的),做两个选择一个,得到一个数组中的所有线程,然后另一个这确实是一种数组选择,但这也不是我真正想要的。如果可能,我想将其保留在一个查询中。

标签: php mysql sql


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多