获取与供应商的外键值相同的最后插入(最新添加)的合同ID

时间:2018-11-08 09:25:08

标签: mysql sql foreign-keys

我有一个名为c_supplier_contract的表
我要做的是,使每个供应商外键值的最后插入的具有相同的值。

例如,下面以蓝色显示我想要的图像的整个表格。
enter image description here


这就是我想要得到的...为了演示,我只提供了两行,但是表可以有很多这样的行...

enter image description here

如何编写mysql查询以获得这种结果?非常感谢任何人的帮助!

1 个答案:

答案 0 :(得分:0)

我不知道什么是“最后插入时间”,所以我选择了最后一个supp_date_expired
而db-fiddle链接是here

希望对您有所帮助。

select supp_cont_id,
       supp_cont_desc,
       supp_date_signed,
       supp_date_expired,
       supp_fk_id
  from temptable
 where (supp_fk_id, supp_date_expired) in (select supp_fk_id, max(supp_date_expired)
                                             from temptable
                                            where ifnull(supp_fk_id, 0) != 0
                                            group by supp_fk_id
                                           having count(1) > 1);