【问题标题】:SQL Join with where clause in joined tableSQL Join 与联接表中的 where 子句
【发布时间】:2017-11-18 18:13:23
【问题描述】:

世界。

我在这里有两个表,分别称为驱动程序和签到。 checkin 表的 d_id 字段保存了驱动表中条目的 id。

在我的查询中,我尝试加入表并对加入的表执行 where 条件。

到目前为止,我有这个查询(我无法加入表,加入表上的 where 部分是在我实现这一点之后出现的)

SELECT checkin.id, checkin.d_id, checkin.place, ( 3959 * acos( cos( radians(8.9551889) ) * cos( radians( lati ) )
* cos( radians( longi ) - radians(76.9902276) ) + sin( radians(8.9551889) ) * sin(radians(lati)) ) ) AS distance
FROM checkin WHERE status != 1
INNER JOIN drivers ON drivers.id = checkin.d_id
HAVING distance < 10 
ORDER BY distance
LIMIT 0 , 20

这个查询在没有内部连接的情况下工作,但我不确定我在这里做错了什么。如果有人能指出来,那会很有帮助。 谢谢。

【问题讨论】:

  • 如果您使用 where 子句,则无需写“Having”。你没有使用 group by 所以有和 where 子句的工作方式相同。在内连接后也使用 where 子句。 --- 如果您的驱动程序表没有返回数据而不是您希望结果使用左连接。

标签: php mysql join


【解决方案1】:

你应该在inner join之后使用where子句:

SELECT checkin.id, checkin.d_id, checkin.place, ( 3959 * acos( cos( radians(8.9551889) ) * cos( radians( lati ) )
* cos( radians( longi ) - radians(76.9902276) ) + sin( radians(8.9551889) ) * sin(radians(lati)) ) ) AS distance
FROM checkin 
INNER JOIN drivers ON drivers.id = checkin.d_id
WHERE status != 1
HAVING distance < 10 
ORDER BY distance
LIMIT 0 , 20;

替代查询:

 SELECT checkin.id, checkin.d_id, checkin.place, ( 3959 * acos( cos( radians(8.9551889) ) * cos( radians( lati ) )
    * cos( radians( longi ) - radians(76.9902276) ) + sin( radians(8.9551889) ) * sin(radians(lati)) ) ) AS distance
    FROM (select *from checkin where status!=1) checkin
    INNER JOIN drivers ON drivers.id = checkin.d_id
    HAVING distance < 10 
    ORDER BY distance
    LIMIT 0 , 20;

【讨论】:

  • 谢谢,查询运行没有错误,但是它没有从驱动程序表中返回数据。
  • @HaiderAli 这些字段都正确吗:checkin.id, checkin.d_id?
  • @aendeerei 我想通了,我不得不在 select 语句中提到我想要从连接表中得到的字段
  • @HaiderAli 完美。那么祝你好运。
猜你喜欢
  • 2011-04-14
  • 1970-01-01
  • 2016-02-05
  • 1970-01-01
  • 2017-01-31
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多