douba4275 2015-01-21 11:13
浏览 69
已采纳

php mysql与左外连接

I have two tables in mysql table1 and table2

table1 have the following fields

Field               Type    

intProjectId        int(11)         
intSourceId     int(11)     
intClientId         int(11)     
varProject      varchar(200)    
fltAmount            float              
varAmountType varchar(50)   
dtStart              date       
dtEnd                date   

And table 2 have the following fields

    Field                                   Type

intPercentageId                     int(11)     
intProjectId                        int(11)         
floatPaymentpercentage              float   
ddDate                              datetime

join two table with common project id.If table2 has no records with the particular project id it can joined as null..

Table 1 has project data Table 2 has its percentage of complettion. (Each project has more than one records. ) Project Id -- common field

Iused the following query

SELECT * FROM table1 LEFT OUTER JOIN table2 ON table1.intProjectId = table2.intProjectId
GROUP BY table1.varProject ORDER BY table2.intPercentageId DESC

Here i get the output as percentage table returns the first record for each project. I need the last inserted record for the table 2.

table1 ==> project id 5 In table 2 has 3 records for project Id 5. I want to ge the last record from the table2. Now it returns the first record from table 2

How to change the query. Please help me to fix this.

  • 写回答

3条回答 默认 最新

  • du1068 2015-01-22 06:39
    关注

    Calculate the maximum record for each project in table2 and use that information to get the latest record. Here is a method that uses group by:

    select t1.*
     from table1 t1 join
     table2 t2
     on t1.intProjectId = t2.intProjectId join
     (select t2.intProjectId, max(intPercentageId) as maxpi
      from table2 t2
      group by t2.intProjectId
     ) tt2
     on t2.intProjectId = tt2.maxpi;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line