比较MySQL中不同表中的两列

时间:2015-03-26 09:17:47

标签: mysql

我有两张桌子

vehicles

regno     make      status

KBT567K   ISUZU     operating
KAD897L   DOGDE     operating
KAT876K   JAGUAR    grounded
KAW564H   FERRARI   operating

contributions

regno      amount    timestamp

KBT567K     200      2015-03-24 18:10:13 
KAD897L     100      2015-03-24 12:32:16
KBT567K     150      2015-03-25 11:06:32

我正在尝试提取一个查询,其中我只从regno 2015-03-25 status 'operating' select regno from vehicles where regno not in ( select contributions.regno from contributions,vehicles WHERE DATE_FORMAT(contributions.timestamp,'%Y-%m-%d') > '2015-03-25' AND DATE_FORMAT(contributions.timestamp,'%Y-%m-%d') > '2015-03-24' ) AND vehicles.status = 'operating' ORDER BY vehicles.regno asc 列表p>

我在下面尝试过此查询,但不起作用。任何帮助将受到高度赞赏

{{1}}

3 个答案:

答案 0 :(得分:1)

您可以使用JOIN

select vehicles.regno
from vehicles
LEFT JOIN contributions ON vehicles.regno = contributions.regno
WHERE DATE_FORMAT(contributions.timestamp,'%Y-%m-%d') != '2015-03-25'
AND WHERE vehicles.status = "operating"
ORDER BY vehicles.regno asc 

答案 1 :(得分:1)

你可以尝试这个SQL:

select DISTINCT regno 
from vehicles
where status = 'operating' AND regno in (select regno from contributions WHERE DATE_FORMAT(timestamp,'%Y-%m-%d') != '2015-03-25') 
ORDER BY regno asc 

答案 2 :(得分:0)

我为此制定了解决方案

 Select DISTINCT regno from vehicles where status = 'operating' AND vehicles.regno not in (select regno from contributions WHERE DATE_FORMAT(timestamp,'%Y-%m-%d') > '2015-03-24') and DATE_FORMAT(timestamp,'%Y-%m-%d') != '2015-03-25' ORDER BY regno asc

谢谢大家的时间。干杯