我有这个数据库表
CREATE TABLE IF NOT EXISTS `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`inherit` enum('Y','N') NOT NULL DEFAULT 'N',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
--
-- Dumping data for table `category`
--
INSERT INTO `category` (`id`, `parent_id`, `name`, `inherit`) VALUES
(1, 0, 'Fruits', 'N'),
(2, 0, 'Electronics', 'N'),
(3, 0, 'Furniture', 'N'),
(4, 0, 'Garden', 'N'),
(5, 1, 'Apples', 'N'),
(6, 1, 'Bananas', 'N'),
(7, 5, 'Green Apples', 'Y'),
(8, 5, 'Red Apples', 'N'),
(9, 2, 'Mobiles', 'Y'),
(10, 2, 'Televisions', 'N'),
(11, 9, 'Android', 'N'),
(12, 9, 'iPhone', 'Y'),
(13, 7, 'One Dozen Green Apples', 'Y'),
(14, 7, 'Two Dozens Green Apples', 'N');
还有另一个表,我保留 user_id,category_id 例如 user_id 1000 可以看到 1 和 5,我将此信息放在会话中,以便我的查询变为
SELECT *
FROM `category`
WHERE id
IN ( 1, 5 )
这个查询显示Fruits > Apples
- 这一切都很好。但是,我已经标记了“ Green Apples
”,Inherit = 'Yes'
因此用户 1000 也应该看到“ Green Apples
”,但看不到“ Red Apples
”。如果青苹果下有标记为继承 = 'Y' 的子类别......例如“一打青苹果”也应该列出!!
我想试一试 UNION,但不知道如何让 UNION 更深 2 级以上……
SELECT * FROM (
SELECT *
FROM `category`
WHERE id
IN ( 1, 5 )
UNION
SELECT c.*
FROM `category` c
INNER JOIN `category` parent ON parent.id = c.id AND c.inherit = 'Y'
WHERE c.parent_id
IN ( 1, 5 )
) all_cats
你会给我什么建议?如果这会使查询更容易,我会更改开放表结构吗?谢谢