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でない場合は、子ではなく親を返したいです。理想的には、このクエリにも重複がないでしょう...

単一のクエリ内で可能ですか?

サーバーサイド重要な場合は、PHPYiiを使用します...

4

2 に答える 2

0

クエリを2つに分割してみてください。

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 に答える