0

私はこのテーブルを手に入れました:

CREATE TABLE 'category' (
    'id' INT(11) NOT NULL AUTO_INCREMENT,
    'parent_category_id' INT(11) NULL DEFAULT NULL,
    'name' VARCHAR(100) NOT NULL,
    PRIMARY KEY ('id'),
    INDEX 'parent_category_id' ('parent_category_id'),
    CONSTRAINT 'category_ibfk_1' FOREIGN KEY ('parent_category_id') REFERENCES 'category' ('id')
) COLLATE='utf8_general_ci' ENGINE=InnoDB;

サブカテゴリが 3 つ未満 (深さなし) のカテゴリを選択する方法と、子要素を持たないカテゴリを選択する方法を教えてください。ありがとう!

4

1 に答える 1

1

3 人未満の場合:

select parent.*
from category parent left outer join
     category child
     on parent.id = child.parent_category_id
group by parent.id
having count(child.id) < 3

カテゴリがない場合:

select parent.*
from category parent left outer join
     category child
     on parent.id = child.parent_category_id
where child.id is null
于 2013-08-17T22:33:18.813 に答える