另一个MYSQL加入问题

时间:2012-09-13 05:01:11

标签: mysql join

大家好,我真的很难让下面的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

我已经尝试了很多这种组合但是我很难过并且正在寻找帮助吗?

3 个答案:

答案 0 :(得分:2)

  1. JOIN应该在FROM tablename或其他JOIN
  2. 之后立即关注
  3. 在这种情况下,您应该使用WHERE,而不是HAVING
  4. 你应该JOIN users u,而不是子查询(在这种情况下没有意义)

答案 1 :(得分: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 <=。请注意,只有在您拥有SUM,COUNT等聚合函数时才使用 HAVING子句进行过滤。任何正常的过滤操作都使用 WHERE子句

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>

希望你明白。

答案 2 :(得分: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