简体   繁体   English

MySQL LEFT JOIN,联接表中没有满意的匹配项

[英]MySQL LEFT JOIN and no satisfied match in the joining table

I have a strange set of circumstances that I don't seem to be able to build a query for. 我遇到了一系列奇怪的情况,似乎无法为其建立查询。 Help is appreciated. 感谢帮助。

Here is my query as it currently sits: 这是我目前的查询:

SELECT * 
FROM vehicle 
LEFT JOIN vehicle_insurance AS ins
ON vehicle.id=ins.vehicle_id
WHERE vehicle.id='{$vid}' 
AND ( ins.effective<='{$date}' OR ins.effective IS NULL )
AND ( ins.expires>='{$date}' OR ins.expires IS NULL )

$vid and $date are properly subtituted with valid data. $vid$date将正确替换为有效数据。 What I want to happen is to have the columns from the vehicle table in the response no matter what. 我想发生的是无论如何都要在响应中包含vehicle表中的列。 If I enter a valid date this works. 如果我输入有效日期,则可以使用。 If I enter a date that is not spanned in the insurance table, I still want to get the general info about the vehicle, but instead I get an empty record set. 如果我输入的日期不在保险表中,则我仍想获取有关车辆的一般信息,但会得到一个空的记录集。

I thought that putting the IS NULL clauses might help this, but the problem is that the LEFT JOIN does match at least one record in the insurance table, but consequently there is no matching policy that spans the requested date. 我认为放置IS NULL子句可能有助于解决此问题,但是问题是LEFT JOIN确实与保险表中的至少一条记录匹配,但是因此没有跨越请求日期的匹配策略。

How can I improve my query? 如何改善查询?

I think you should move your ins conditions into the ON statement 我认为您应该将ins条件移到ON语句中

SELECT * 
FROM vehicle 
LEFT JOIN vehicle_insurance AS ins
ON vehicle.id=ins.vehicle_id AND ins.effective<='{$date}' AND  ins.expires>='{$date}'
WHERE vehicle.id='{$vid}'

I don't use MySQL but if I was doing this on SQL Server I would probably create a subquery that had your insurance details in with the where clause in there, then join vehicles to that. 我不使用MySQL,但是如果我在SQL Server上执行此操作,则可能会创建一个子查询,该子查询中的where子句中包含您的保险详细信息,然后将车辆加入其中。

The syntax my be wrong here but something like this. 语法我在这里是错误的,但是像这样。

SELECT * 
FROM vehicle 
LEFT JOIN 
(
   SELECT * FROM vehicle_insurance 
   WHERE ( ins.effective<='{$date}' OR ins.effective IS NULL )
     AND ( ins.expires>='{$date}' OR ins.expires IS NULL ) 
) AS ins
ON vehicle.id=ins.vehicle_id
WHERE vehicle.id='{$vid}' 

This way the insurance details are filtered prior to the left join to the vehicle. 这样,保险细节在左连接到车辆之前就被过滤掉了。

There are more elegant ways but this way usually saves on my limited brain power! 还有更多优雅的方法,但是这种方法通常可以节省我有限的脑力!

Al. 人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM