MySQL - посчитать количество концов у дерева
where
not exists
(select * from tree
where
parentid=t.id)
from tree tнепонял синтаксиса, или нужна запятая, тогда 2 таблицы, но у меня одна таблица, или объясни, что это за тема на пальцах, плз..
where
where
обязательно попробую...
спасибо
Вот пример из референса:
SELECT DISTINCT store_type FROM Stores S1
WHERE NOT EXISTS (
SELECT * FROM Cities WHERE NOT EXISTS (
SELECT * FROM Cities_Stores
WHERE Cities_Stores.city = Cities.city
AND Cities_Stores.store_type = Stores.store_type;
http://dev.mysql.com/doc/mysql/en/exists-and-not-exists-subqueries.html
можно переписать так:
SELECT
COUNT(DISTINCT t1.id)
FROM tree AS t1
LEFT JOIN tree AS t2 ON (t1.id = t2.parentid)
WHERE t2.id IS NULL
это, до кучи, все листья
SELECT
t1.id, COUNT(t2.id) AS num_of_children
FROM tree AS t1
LEFT JOIN tree AS t2 ON (t1.id = t2.parentid)
GROUP BY t1.id
HAVING num_of_children = 0
А после какой версии мускул рюхает джойны?
а вот субзапросы только очень недавно
Starting with MySQL 4.1, all subquery forms and operations that the SQL standard requires are supported, as well as a few features that are MySQL-specific.
With MySQL versions prior to 4.1, it was necessary to work around or avoid the use of subqueries. In many cases, subqueries can successfully be rewritten using joins and other methods. See Section 13.2.8.11, “Rewriting Subqueries as Joins for Earlier MySQL Versions”.
4.1.1 вышел в декабре 2003, так что возможно всё будет ок
так что придется заюзать join
Оставить комментарий
stm7884696
Есть структура дерева:id (int, autoincriment)
parentid (id родителя)
data (любые данные)
Надо посчитать количество концов ветвей (элементов, которые не являются родителями для других)
Как это можно сделать одним запросом ?