在MySQL查询中找到多个" OR"

时间:2017-01-24 09:52:17

标签: mysql sql

我需要在MySQL查询中找到部分或完全匹配。我正在使用' OR'在多个表格中执行查询并且需要知道是否已经满足所有条件或只是其中一些条件。

我认为最简单的方法是创建一个名为“部分'这将是0或1(如果我错了,请随意纠正我。)

这是我的问题:

SELECT 
  id, confirmed, name, addressLine1, addressLine2, addressCity, addressPostcode,
  addressLat, addressLon,
  (6371 * acos( cos( radians( '53.649779' ) ) 
              * cos( radians( addressLat ) )
              * cos( radians( addressLon ) - radians( '-1.6026266' ) )
              + sin( radians( '53.649779' ) ) * sin( radians( addressLat ) ) ) 
  ) distance 
FROM TABLE_NAME 
WHERE active = '1' 
  AND deleted = '0' 
  AND 
  (
    id < 0 
   OR 
    id IN 
    (
      SELECT establishmentID 
      FROM appEstablishmentDrinks 
      WHERE active = '1' 
        AND deleted = '0' 
        AND manufacturerDrinkID IN (101) 
      GROUP BY establishmentID 
      HAVING count(distinct manufacturerDrinkID) = 1
    ) 
   OR
    id IN 
    (
      SELECT establishmentID 
      FROM appEstablishmentFacilities 
      WHERE active = '1' 
      AND deleted = '0' 
      AND facilityID IN (37)
    )
  ) 
HAVING distance < '15'

1 个答案:

答案 0 :(得分:2)

在MySQL中true = 1且false = 0.因此,只需添加条件:(id < 0) + (id in (...)) + (id in (...))并检查您是否获得所有三场或更少的匹配。

SELECT
  id, confirmed, name, addressLine1, addressLine2, addressCity, addressPostcode,
  addressLat, addressLon, distance,
  case when count_matches = 3 then 'full' else 'partial' end as matching
FROM
(
  SELECT 
    id, confirmed, name, addressLine1, addressLine2, addressCity, addressPostcode,
    addressLat, addressLon,
    (6371 * acos( cos( radians( 53.649779 ) ) 
                * cos( radians( addressLat ) )
                * cos( radians( addressLon ) - radians( -1.6026266 ) )
                + sin( radians( 53.649779 ) ) * sin( radians( addressLat ) ) ) 
    ) as distance,
    (id < 0 )
     + 
    (
      id IN 
      (
        SELECT establishmentID 
        FROM appEstablishmentDrinks 
        WHERE active = 1 
          AND deleted = 0 
          AND manufacturerDrinkID IN (101) 
        GROUP BY establishmentID 
        HAVING count(distinct manufacturerDrinkID) = 1
      ) 
    )
     +
    (
      id IN 
      (
        SELECT establishmentID 
        FROM appEstablishmentFacilities 
        WHERE active = 1 
        AND deleted = 0 
        AND facilityID IN (37)
      )
    ) as count_matches
  FROM TABLE_NAME 
  WHERE active = 1 
    AND deleted = 0
) x
WHERE distance < 15
AND count_matches > 0;