mysql - 如何在 where/and 子句中使用 sql 选择数据

标签 mysql sql

我有这个运行良好的 mysql 代码,但我想知道如何避免两次执行 RAW 数据计算,这是我的代码

SELECT `users`.*, ( 3959 * ACOS(COS(RADIANS(43.9743)) *
  COS(RADIANS(locations.lat)) * 
  COS( RADIANS(-75.9122) - RADIANS(locations.LONG)) +
                              SIN(RADIANS(43.9743)) *
  SIN(RADIANS(locations.lat) )) ) AS distance 
FROM   `users` 
INNER JOIN `addresses` ON `users`.`id` = `addresses`.`user_id` 
LEFT JOIN `locations` ON `addresses`.`zip` = `locations`.`zip` 
WHERE  `type` = 'doctor' 
  AND ( 3959 * ACOS(COS(RADIANS(43.9743)) * COS(RADIANS(locations.lat)) *
    COS( RADIANS(-75.9122) - RADIANS(locations.LONG)) +
    SIN(RADIANS(43.9743)) * SIN(RADIANS(locations.lat) )) ) < 100
  AND `users`.`deleted_at` IS NULL 
ORDER BY distance ASC
LIMIT  15 OFFSET 0 

如您所见,我使用了两次此计算 ( 3959 * ACOS(COS(RADIANS(43.9743)) * COS(RADIANS(locations.lat)) * COS( RADIANS(-75.9122) - RADIANS(locations.LONG)) + SIN(RADIANS(43.9743)) * SIN(RADIANS(locations.lat) )) )ANDSELECT 语句上。

我试过 AND distance < 100但我收到一条错误消息,说列不存在。

感谢任何帮助

最佳答案

您可以将计算列放置在可从中访问指定列的子查询(特别是“表表达式”)中。

例如:

select *
from ( -- the definition of table expression "x" starts
  SELECT `users`.*, ( 3959 * ACOS(COS(RADIANS(43.9743)) *
    COS(RADIANS(locations.lat)) * 
    COS( RADIANS(-75.9122) - RADIANS(locations.LONG)) +
                              SIN(RADIANS(43.9743)) *
    SIN(RADIANS(locations.lat) )) ) AS distance 
  FROM   `users` 
  INNER JOIN `addresses` ON `users`.`id` = `addresses`.`user_id` 
  LEFT JOIN `locations` ON `addresses`.`zip` = `locations`.`zip` 
) x -- the definition of table expression "x" ends
WHERE `type` = 'doctor' 
  AND distance < 100 -- here we use the "distance" column
  AND `users`.`deleted_at` IS NULL 
ORDER BY distance ASC
LIMIT  15 
OFFSET 0 

在 MySQL 8.x 中,您可以使用 CTE(公用表表达式),如:

with
x as (
  SELECT `users`.*, ( 3959 * ACOS(COS(RADIANS(43.9743)) *
    COS(RADIANS(locations.lat)) * 
    COS( RADIANS(-75.9122) - RADIANS(locations.LONG)) +
                              SIN(RADIANS(43.9743)) *
    SIN(RADIANS(locations.lat) )) ) AS distance 
  FROM   `users` 
  INNER JOIN `addresses` ON `users`.`id` = `addresses`.`user_id` 
  LEFT JOIN `locations` ON `addresses`.`zip` = `locations`.`zip` 
)
SELECT *
FROM x
WHERE  `type` = 'doctor' 
  AND distance < 100
  AND `users`.`deleted_at` IS NULL 
ORDER BY distance ASC
LIMIT  15 
OFFSET 0 

关于mysql - 如何在 where/and 子句中使用 sql 选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61372741/

相关文章:

sql从 View 和表中选择

Mysql 文本存储?

mysql - 如何将一张表与一对多表合并为一条记录结果

mysql - 鞋子网上商店的数据库规范化

mysql - 为什么我的 MySQL 查询排序不正确?

php - 累加并除以 60 的整数

sql - 什么是基数以及它如何影响性能 (SQL Server)?

MySQL:从单个表的2列中设置2个变量

java - Hibernate View 在应用程序和工作台中显示不同的结果

mysql创建表id自增报错