0

嗨,我真的很难让以下 sql 查询正常工作,如果我对此进行了混搭,我提前道歉,但我仍在学习 SQL 的全部高级领域。

这是我的代码...

"SELECT *,(((acos(sin((".$latitude."*pi()/180)) * 
sin((`latitude`*pi()/180))+cos((".$latitude."*pi()/180)) * 
cos((`latitude`*pi()/180)) * cos(((".$longitude."- `longitude`)*pi()/180))))
*180/pi())*60*1.1515) as distance 
FROM `locations`  l HAVING distance <= '".$distance."' JOIN 
(SELECT * users) u
ON (l.id = u.basic_location)
            WHERE u.id != A $AND2
            ORDER BY distance ASC"

我不断收到以下错误消息...

You have an error in your SQL syntax; check the manual that corresponds to your 
MySQL server version for the right syntax to use near 
'JOIN (SELECT * users) u ON (l.id = u.basic_location) WHERE u.id' at line 1

我已经尝试了很多这种组合,但我被难住了,正在寻找一些帮助?

4

3 回答 3

2
  1. JOIN应该紧随FROM tablename其后JOIN
  2. 你应该使用WHERE, 不是HAVING在这种情况下
  3. 你应该JOIN users u,而不是子查询(在这种情况下它没有意义)
于 2012-09-13T05:06:06.923 回答
1

试试这个

    "SELECT *,

        (((( SELECT 
        acos(
            sin((".$latitude."*pi()/180)) * 
            sin((`latitude`*pi()/180))+
            cos((".$latitude."*pi()/180)) * 
            cos((`latitude`*pi()/180)) * 
            cos(((".$longitude."- `longitude`)*pi()/180))
            ))*180/pi())*60*1.1515) as distance
    FROM `locations`  l )X
    JOIN users u
ON (X.id = u.basic_location)
WHERE u.id != A $AND2
AND distance <= '".$distance."'
ORDER BY distance ASC"

变化

1 )HAVING distance <=需要WHERE distance <=修改为_

2)连接语法是:

SELECT t1.*
FROM Table1 t1
JOIN Table2 t2
ON t1.Id = t2.Id
Where t1.<Some condition>
AND t2.<some Condition>

并不是

SELECT t1.*
FROM Table1 t1 Where t1.<Some condition>
JOIN Table2 t2
ON t1.Id = t2.Id
Where t2.<some Condition>

如果您需要在加入之前从第一个表中进行过滤,请执行以下操作

SELECT X.*,Y.* 
FROM (SELECT * FROM Table1 t1 Where t1.<Some condition>) X
JOIN (SELECT * FROM Table2 t2) Y
ON X.Id = Y.Id
Where Y.<some Condition>

希望你能理解。

于 2012-09-13T05:08:44.710 回答
1
select * from
(SELECT *,
(((acos(sin((".$latitude."*pi()/180)) * 
sin((`latitude`*pi()/180))+
cos((".$latitude."*pi()/180)) * 
cos((`latitude`*pi()/180)) * 
cos(((".$longitude."- `longitude`)*pi()/180))))*
180/pi())*60*1.1515) as distance 
FROM `locations`  l  INNER JOIN 
`users` u
ON l.id = u.basic_location
WHERE u.id != A $AND2) derived_table dt
where dt.distance <= '".$distance."'
ORDER BY dt.distance ASC
于 2012-09-13T05:17:21.480 回答