所以我有一个非常复杂的查询,我希望返回具有最高订单量的指定半径内的前10个产品。到目前为止,我有一个工作查询,以获取所有产品在一定范围内(使用原始SQL查询)。现在的问题是按订单数量排序。以下是查询。我可以根据需要提供更多细节。提前谢谢!
var prods = _context.Products
.FromSql($"SELECT p.* FROM (SELECT s.\"storefrontID\", z.radius, z.distance_unit * DEGREES(ACOS(COS(RADIANS(z.latpoint)) * COS(RADIANS(a.lat)) * COS(RADIANS(z.longpoint - a.lon)) + SIN(RADIANS(z.latpoint)) * SIN(RADIANS(a.lat)))) AS distance FROM public.\"Addresses\" AS a, public.\"Storefronts\" AS s JOIN (SELECT {lat} AS latpoint, {lon} AS longpoint, {radius} AS radius, {distance_unit} AS distance_unit) AS z ON 1=1 WHERE s.\"addressID\" = a.\"addressID\" AND a.lat BETWEEN z.latpoint - (z.radius / z.distance_unit) AND z.latpoint + (z.radius / z.distance_unit) AND a.lon BETWEEN z.longpoint - (z.radius / (z.distance_unit * COS(RADIANS(z.latpoint)))) AND z.longpoint + (z.radius / (z.distance_unit * COS(RADIANS(z.latpoint))))) AS a, public.\"Storefronts\" AS s WHERE distance <= radius AND s.\"storefrontID\" = a.\"storefrontID\"")
.Include(p => p.orderProductConnectors.Count())
.OrderByDescending(p => p.orderProductConnectors)
.AsNoTracking()
.ToList();
值得注意的是,我正在使用postgreSQL作为我的数据库解决方案。
答案 0 :(得分:1)
猜测:
var prods = _context.Products
.FromSql($"SELECT p.* FROM (SELECT s.\"storefrontID\", z.radius, z.distance_unit * DEGREES(ACOS(COS(RADIANS(z.latpoint)) * COS(RADIANS(a.lat)) * COS(RADIANS(z.longpoint - a.lon)) + SIN(RADIANS(z.latpoint)) * SIN(RADIANS(a.lat)))) AS distance FROM public.\"Addresses\" AS a, public.\"Storefronts\" AS s JOIN (SELECT {lat} AS latpoint, {lon} AS longpoint, {radius} AS radius, {distance_unit} AS distance_unit) AS z ON 1=1 WHERE s.\"addressID\" = a.\"addressID\" AND a.lat BETWEEN z.latpoint - (z.radius / z.distance_unit) AND z.latpoint + (z.radius / z.distance_unit) AND a.lon BETWEEN z.longpoint - (z.radius / (z.distance_unit * COS(RADIANS(z.latpoint)))) AND z.longpoint + (z.radius / (z.distance_unit * COS(RADIANS(z.latpoint))))) AS a, public.\"Storefronts\" AS s WHERE distance <= radius AND s.\"storefrontID\" = a.\"storefrontID\"")
.OrderByDescending(p => p.orderProductConnectors.Count())
.AsNoTracking()
.ToList();