如何获取mysql中没有子节点的最终类别?
我想从下表中得到的结果是
3,5,6。
他们没有儿童类别。
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `cat`
-- ----------------------------
DROP TABLE IF EXISTS `cat`;
CREATE TABLE `cat` (
`categories_id` int(10) NOT NULL auto_increment,
`parent_id` int(10) NOT NULL default '0',
PRIMARY KEY (`categories_id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of cat
-- ----------------------------
INSERT INTO `cat` VALUES ('1', '0');
INSERT INTO `cat` VALUES ('2', '1');
INSERT INTO `cat` VALUES ('3', '1');
INSERT INTO `cat` VALUES ('4', '2');
INSERT INTO `cat` VALUES ('5', '0');
INSERT INTO `cat` VALUES ('6', '4');
答案 0 :(得分:2)
select * from cat where categories_id not in (select parent_id from cat)
这是你要求的吗?
同样可以通过
实现select * from cat child
left join cat parent on child.categories_id = parent.parent_id
where parent.parent_id is null
答案 1 :(得分:1)
使用左自联:
select c1.categories_id
from cat c1
left join cat c2
on c2.parent_id = c1.categories_id
where c2.categories_id IS NULL
答案 2 :(得分:0)
select * from cat where categories_id = "0";
或者你可以做Akhil的查询。如果这是你一直在问的问题