CREATE TABLE IF NOT EXISTS `site_location` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`level` int(11) NOT NULL,
`lft` int(11) NOT NULL,
`rgt` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
///DATA
INSERT INTO `site_location` (`id`, `level`, `lft`, `rgt`, `name`) VALUES
(1, 0, 1, 24, 'United Kingdom'),
(2, 1, 2, 19, 'London'),
(3, 2, 13, 14, 'Central London'),
(4, 2, 11, 12, 'East London'),
(5, 2, 9, 10, 'North London'),
(6, 2, 7, 8, 'North West London'),
(7, 2, 5, 6, 'South East London'),
(8, 2, 3, 4, 'West London'),
(9, 2, 15, 18, 'South West'),
(10, 3, 16, 17, 'Battersea'),
(11, 1, 20, 23, 'Brighton'),
(12, 2, 21, 22, 'Guildford');
CREATE TABLE IF NOT EXISTS `ads` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category_id` int(11) NOT NULL,
`location` int(11) NOT NULL,
`title` varchar(255) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`id`,`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSERT INTO `ads` (`id`, `category_id`, `location`, `title`) VALUES
(1, 7, 10, 'Test1'),
(2, 9, 3, 'Test2'),
(3, 12, 10, 'Test3'),
(4, 13, 4, 'Test4');
当 ID 为 ID=1 时以这种方式返回
[ United Kingdom(4) ]
London(4)
Brighton(0)
当 ID 为 ID = 2
United Kingdom(4)
[ London(4) ]
South West(2)
Central London(1)
East London(1)
Brighton(0)
so when is selected "London" I need all its siblings and all its children
选择“西南”时相同,我需要它的所有兄弟姐妹所有它的孩子,它的父母所有它的父母兄弟姐妹
United Kingdom(4)
London(4)
[ South West(2) ]
Battersea(2)
Central London(1)
East London(1)
Brighton(0)
以及该位置有多少广告,例如在英国必须有 4 个,因为表格中的所有广告都是 4 个,西南必须有 2 个,因为在巴特西有 2 个
当 id 为 11 时
United Kingdom(4)
London(4)
[ Brighton(0) ]
Guildford(0)
我有一个查询:西南 lft:15, rgt:18, level:2
SELECT
node.id,
node.alias,
node.level,
node.name,
COUNT(ads.id) as ads,
IF(node.lft = node.rgt-1, "0", "1") AS `has_children`
FROM
site_location AS parent LEFT JOIN
ads as ads ON (parent.id = ads.location),
site_location AS node
WHERE
parent.lft BETWEEN node.lft AND node.rgt
AND
parent.lft BETWEEN 15 AND 18
AND
node.level > 0
AND
node.level < 2 + 3
GROUP BY node.id
ORDER BY node.lft
这将返回
London(4)
South West(2)
Battersea(2)
我需要这样
London(4)
South West(2)
Battersea(2)
Brighton(0)
是否可以通过单个查询来做到这一点:?如果有人可以提供帮助,那就太好了。提前致谢!