我正在尝试在SQL中构建一个相当复杂的查询,作为一个初学者,我将非常感谢您提供一些帮助来构建它。

我正在努力实现以下目标:





1 /使用毕达哥拉斯使用笛卡尔纬度和经度坐标计算target_postcodes表中的邮政编码-例如E1 1AA-和population_postcodes表中的所有邮政编码之间的distance

SQRT( POW(MY_Y_AXIS - Y_AXIS, 2) + POW(MY_X_AXIS-X_AXIS, 2) )


2 /使用这些distance值创建一个新列,

not sure how to do that step


2-bis /根据获得的population_postcodes值对distance中的邮政编码进行排序,

not sure how to do that step


3 /从最接近的邮政编码开始,将填充列中的值添加到E1 1AA的running_count列UNTIL running_count> Number_of_beds中,

建议的运行计数查询-但缺少上述中断条件:

SELECT distance, Population,
 (SELECT sum(population_postcodes.Population)) AS Total

FROM population_postcodes
WHERE population_postcodes.distance <= T1.distance) AS Total

FROM population_postcodes AS T1


4 /创建一个新表,其中包含邮政编码E1 1AA(target_postcode)和添加到我们的运行计数中的最后一个邮政编码的距离值。

最后,我需要在整个target_postcodes表上循环此查询。

非常感谢您帮助新手!

最佳答案

1.,2.若要将表放在一起并在它们之间执行操作,您需要使用Join
http://dev.mysql.com/doc/refman/5.0/en/join.html
否则您的公式是正确的。要将其创建为查询中的列,只需将其写在projection(select)部分中。
例:

select
population_postcodes.*,
target_postcodes.*,
SQRT( POW(population_postcodes.longitude- target_postcodes.longitude, 2) + POW(population_postcodes.latitude-target_postcodes.latitude, 2) ) as distance
from population_postcodes JOIN target_postcodes


点2之二。以column_name asc / desc的Order结尾
http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html

要点3.将所有内容都写为sub-query,然后仅在顶部查询中选择所需的内容。另请参阅HAVING
http://dev.mysql.com/doc/refman/5.0/en/subqueries.html
http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html

第4点。研究创建表和应用已接近结果的方法

create table mytablename
select ... my projection columns
from ...


http://dev.mysql.com/doc/refman/5.1/en/create-table.html

08-04 15:04