简体   繁体   English

比较MySQL不同表中的两列

[英]Compare two columns in different tables in MySQL

I have two tables 我有两张桌子

Table vehicles vehicles

regno     make      status

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

Table contributions 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

I am trying to pull a query where I only get a list of regno from table vehicles that have not contributed on 2015-03-25 while their status is 'operating' 我想拉一查询,我只能得到一个列表regno从表中的车辆还没有上贡献了2015-03-25 ,而他们的status'operating'

I have tried this query below but doesn't work. 我已经在下面尝试了此查询,但无法正常工作。 Any help will be highly appreciated 任何帮助将不胜感激

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 

You can use JOIN 您可以使用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 

You can try this SQL: 您可以尝试以下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 

I worked out the solution for this 我为此解决了

 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

Thanks all for your time. 感谢您的宝贵时间。 Cheers 干杯

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

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