这是一个表架构:
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';
我想选择Tags但是如果parent_id是NOT NULL,我想返回父代而不是子代。理想情况下,此查询也没有重复...
是否可以在单个查询中使用?
服务器端我使用PHP Yii,如果重要的话......
答案 0 :(得分: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
...)
而不是...
应该是您需要的其他过滤选项。
答案 1 :(得分:0)
使用COALESE
示例,(简化查询)
SELECT COALESCE(parent_ID, iD)
FROM tag