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条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大