如何在一个查询中从两个表中获取记录

时间:2016-02-17 09:11:13

标签: php mysql

我有两张桌子

  1. rental_detail - > [idBuildingFloorFlate_noNamedoj]
  2. rental_detail存储此人的信息 这是rental_detail

    |id|name|building|Floor|Flate_no|doj |1 |aana| C | 1st |c-101 |06-12-2015

    并在

    1. Monthly_rent - > [idBuildingFloorFlate_nodate]存储每月每月租金的详细信息
    2. 这是month_rent

      |id|building|Floor|Flate_no|date |rent| |1 | C | 1st |c-101 |02-01-2016|2000 |2 | C | 1st |c-101 |03-02-2016|2000 |1 | C | 1st |c-101 |06-12-2015|2000

      我需要Monthly_rent的最长日期以及rental_detail的人的所有信息,其中建筑物为c,楼层为1,flate为c-101

      我尝试了此查询:

      select *,max(mr.date) as m 
      from monthly_rent mr 
      Inner join rental_details rd 
         on rd.building='C' and rd.floor = '1st' And rd.flate_no='C-101
      

      我需要这个

      |1|aana|C|1st|c-101|03-02-2016|

      aana在03-02-2016支付最后租金

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT rd .*,mr.date AS mr_date  
FROM rental_details rd 
LEFT JOIN monthly_rent mr 
ON rd.date = (SELECT MAX(date) FROM monthly_rent WHERE building='C' )
WHERE rd.building='C' AND rd.floor = '1st' AND rd.flate_no='C-101'

答案 1 :(得分:0)

试试这个:

select *, max(mr.date) as m 
from monthly_rent mr, rental_details rd
where mr.id = rd.id 
and rd.building='C' 
and rd.floor = '1st' 
and rd.flate_no='C-101'

这应该有效....

答案 2 :(得分:0)

尝试这样,它应该有帮助..

select rd.*,max(mr.date) as m 
from monthly_rent as mr 
LEFT join rental_details as rd ON mr.building = rd.building
WHERE rd.floor = '1st' and rd.flate_no='C-101'