代码之家  ›  专栏  ›  技术社区  ›  Sasha

MySQL-WHERE/和with pivot表

  •  0
  • Sasha  · 技术社区  · 6 年前

    我有三张桌子:

    诊所

    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_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
    

    如果我把 或者 而不是 以及 我有5个诊所,这实际上是我认为应该的工作。我怎样才能得到正确的结果(诊所有两种服务)?我在这里做错什么了?

    1 回复  |  直到 6 年前
        1
  •  0
  •   AlexL    6 年前

    根据 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