选择带有SQL_CALC_FOUND_ROWS和UNION ALL的语句

时间:2014-01-09 10:47:49

标签: mysql

所以我要查找绑定到电子邮件和account_id的数据,如果没有结果,那么只查找account_id。下面的代码正确执行此操作。

 SELECT SQL_CALC_FOUND_ROWS account_id, email, latitude, longitude
 FROM call_module_location
 WHERE email = $email AND `account_id` = $account_id
 UNION ALL
 SELECT account_id, email, latitude, longitude
 FROM call_module_location
 WHERE  FOUND_ROWS() = 0 AND `account_id` = $account_id

但我需要处理3个案例,如果找不到id的数据,在这种情况下我应该通过电子邮件获取数据:

  SELECT SQL_CALC_FOUND_ROWS account_id, email, latitude, longitude
  FROM call_module_location
  WHERE email = $email AND `account_id` = $account_id
  UNION ALL
  SELECT account_id, email, latitude, longitude
  FROM call_module_location
  WHERE  FOUND_ROWS() = 0 AND `account_id` = $account_id
  UNION ALL
  SELECT account_id, email, latitude, longitude
  FROM call_module_location
  WHERE FOUND_ROWS() = 0 AND email = $email";

但它没有用。对此有何解决方案?

1 个答案:

答案 0 :(得分:1)

SELECT account_id, email, latitude, longitude
FROM (SELECT 1 priority, account_id, email, latitude, longitude
      FROM call_module_location
      WHERE email = $email AND `account_id` = $account_id
      UNION
      SELECT 2 priority, account_id, email, latitude, longitude
      FROM call_module_location
      WHERE `account_id` = $account_id
      UNION
      SELECT 3 priority, account_id, email, latitude, longitude
      FROM call_module_location
      WHERE email = $email) u
ORDER BY priority
LIMIT 1

如果您将SQL_CALC_FOUND_ROWS添加到UNION中的第二个查询,原始查询也可能有用。