我正在使用mysql数据库在同一个城市存储公司。我通过使用下面的查询来获取它们。但它并没有像我希望的那样对结果进行排序。 我希望得到的公司能够这样订购:首要的是距离低于<6> 的公司,这些公司必须按 FIELD(sectorid,.... )参数,第二优先级是距离大于6KM且公司必须以相同方式订购的公司(使用FIELD参数)
但我们无法找到解决问题的方法。我在下面显示了正确的结果和我们的查询。如果有人指出我正确的方向,我会很高兴
示例结果必须是这样的:
Company Name: Distance: SectorID:
CompanyA 3 10
CompanyB 2 11
CompanyC 4 13
CompanyX 8 10
CompanyY 7 11
CompanyZ 9 13
我们当前的查询:
SELECT companies.id,
companies.name,
companies.summary,
companies.ratingScore,
companies.companyLogo,
companies.sectorId,
companies.lattitude,
companies.longitude,
companies.address,
company_photos.photoUrl,
(SELECT EXISTS
(SELECT 1
FROM favorites
WHERE favorites.companyId = companies.id
AND userId = 109)) AS favorited,
(SELECT COUNT(*)
FROM ratings
WHERE companies.id = ratings.companyId
AND ratings.isReviewed = 1) AS comments,
(ACOS(SIN(RADIANS(41.212641))*SIN(RADIANS(lattitude))+COS(RADIANS(41.212641))*COS(RADIANS(lattitude))*COS(RADIANS(longitude)-RADIANS(29.020058))) *6371) AS distance
FROM companies
LEFT JOIN company_photos ON company_photos.companyId = companies.id
AND company_photos.photoOrder = 0
WHERE companies.isActivated = 1
AND companies.isReviewed = 1
AND companies.isCustomer = 1
AND companies.isBlocked = 0
ORDER BY FIELD (sectorId, 10, 11, 13, 7, 12, 2, 15, 17), distance
我得到的结果是:
Company Name: Distance: SectorID:
CompanyA 3 10
CompanyX 8 10
CompanyB 2 11
CompanyY 7 11
CompanyC 4 13
CompanyZ 9 13
由于
答案 0 :(得分:0)
order by case when distance<6 then 1 else 2 end, --sorts distance < 6 first and then distance > 6
sectorid --with in each group specified above sorting is on sectorid