我有3张桌子:
诊所
id | name | description | lat | lng | opening_hours| logo | address | city | zip | phone_number | email | url | gmaps_link | marker | created_at | updated_at
服务
id | name | created_at | updated_at
CLINIC_SERVICES
clinic_id | service_id
此查询应返回两个结果,但此刻返回0:
SELECT * FROM
(SELECT clinics.id as cid, clinics.lat, clinics.lng, clinics.opening_hours,
clinics.logo, clinics.address, clinics.city, clinics.name, clinics.description,
clinics.zip, clinics.phone_number, clinics.email, clinics.url, clinics.gmaps_link,
clinics.marker,
countries.full_name AS country,
(6378 * acos(
cos(radians(-33.84801)) * cos(radians(lat)) *
cos(radians(lng) - radians(151.06488)) +
sin(radians(-33.84801)) * sin(radians(lat))))
AS distance
FROM clinics
JOIN countries ON countries.id = clinics.country_id
LEFT JOIN clinics_services ON clinics.id = clinics_services.clinic_id
WHERE clinics_services.service_id = 1 AND clinics_services.service_id = 29
GROUP BY clinics.id
) AS distances
WHERE distance < 50000
ORDER BY distance ASC
如果我输入 OR 而不是 AND ,我将获得5个诊所,这些诊所实际上可以正常工作。如何获得正确的结果(诊所同时提供两种服务)?我在这里做什么错了?
答案 0 :(得分:0)
根据previous similar question,此方法应该有效:
SELECT * FROM
(SELECT clinics.id as cid, clinics.lat, clinics.lng, clinics.opening_hours,
clinics.logo, clinics.address, clinics.city, clinics.name, clinics.description,
clinics.zip, clinics.phone_number, clinics.email, clinics.url, clinics.gmaps_link,
clinics.marker,
countries.full_name AS country,
(6378 * acos(
cos(radians(-33.84801)) * cos(radians(lat)) *
cos(radians(lng) - radians(151.06488)) +
sin(radians(-33.84801)) * sin(radians(lat))))
AS distance
FROM clinics
JOIN countries ON countries.id = clinics.country_id
LEFT JOIN clinics_services ON clinics.id = clinics_services.clinic_id
WHERE clinics_services.service_id = 1 OR clinics_services.service_id = 29
GROUP BY clinics.id
HAVING SUM(clinics_services.service_id = 1) > 0 AND SUM(clinics_services.service_id = 29) > 0
) AS distances
WHERE distance < 50000
ORDER BY distance ASC