[SQL]602(根据属性判定Root/Inner/Leaf)+612(两两距离)
608.树节点
思路
三种分类点的特性:
Root:p_id为空;Inner:既有p_id又是别人的p_id;Leaf:剩下的。
所以代码:
SELECT id, CASE WHEN p_id IS NULL THEN 'Root'
WHEN id IN (SELECT p_id FROM tree) THEN 'Inner'
ELSE 'Leaf' END AS Type
FROM tree;
612. 平面上的最近距离
思路:
将两个表自联结,用POWER(,2)算距离,作为dist。甩掉dist=0的行(这里只能用HAVING),而我暂时还不知原因。
排序取1.(LIMIT 1)
代码
SELECT ROUND(SQRT(POWER(p1.x - p2.x, 2)+POWER(p1.y - p2.y, 2)), 2) AS shortest
FROM point_2d p1, point_2d p2
HAVING shortest != 0
ORDER BY shortest
LIMIT 1;
如果非要用WHERE的话
SELECT ROUND(SQRT(POWER(p1.x - p2.x, 2)+POWER(p1.y - p2.y, 2)), 2) AS shortest
FROM point_2d p1, point_2d p2
WHERE (p1.x, p1.y) != (p2.x, p2.y)
ORDER BY shortest
LIMIT 1;