0

这是一个表模式:

CREATE TABLE `tag` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL COMMENT 'The tag or keyword, always lowercase would be better',
  `community_id` int(10) unsigned NOT NULL COMMENT 'The community this tag belongs to',
  `parent_id` int(10) unsigned DEFAULT NULL COMMENT 'If the tag is an alias to another tag',
  `full_description` text COMMENT 'Content describing tag',
  `short_description` tinytext COMMENT 'Short description of the tag',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name_2` (`name`,`community_id`),
  KEY `FK_tag_community_idx` (`community_id`),
  KEY `FK_tag_tag_idx` (`parent_id`),
  KEY `name` (`name`),
  CONSTRAINT `FK_tag_community` FOREIGN KEY (`community_id`) REFERENCES `community` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT `FK_tag_tag` FOREIGN KEY (`parent_id`) REFERENCES `tag` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COMMENT='Valid tags for a question';

我想选择标签,但如果 parent_id 不是 NULL,我想返回父项而不是子项。理想情况下,这个查询也不会重复......

是否可以在单个查询中进行?

服务器端我使用 PHP Yii,如果重要的话......

4

2 回答 2

0

尝试将您的查询分为两部分:

SELECT *
FROM tag
WHERE parent_id IS NULL AND
      ...

UNION

SELECT *
FROM tag
WHERE parent_id IS NOT NULL AND
      id IN (SELECT parent_id
             FROM tag
             WHERE parent_id IS NOT NULL AND
             ...)

而不是...应该是您需要的其他过滤选项。

于 2012-11-19T09:52:20.857 回答
0

利用COALESE

例如,(简化查询

SELECT  COALESCE(parent_ID, iD)
FROM    tag
于 2012-11-19T09:52:35.320 回答