我是编码的新手,并且遇到了一个SQL问题,希望对您有所帮助。 我正在使用PHP和MySQL。
问题是我将表连接在一起,但是得到的结果却不止一个。我只需要带有付款中最新创建日期的广告。
我想从一个表中展示一些广告,然后与定义了最后一次付款时间的另一表一起加入。
Ad's table:
Id | Title
Payment table:
Id | ad_id | amount | created
我可以在“付款”表中为每个广告保留多个记录,当我退出加入时,每个广告获得的时间与我在“付款”中记录的时间相同。
我已经尝试过了: 1.
SELECT ads.title, payments.created
FROM ads
LEFT JOIN ( Select ads_id, created from payments ORDER BY id asc limit 1) as payments on payments.ads_id = ads.id
-给我正确的广告数量,但仅针对第一个广告创建
SELECT ads.*, payments.created
FROM ads
LEFT JOIN payments ON payments.ads_id=ads.id
-为我的每笔付款记录都提供一个广告
答案 0 :(得分:3)
您需要group by
对广告中的所有付款进行分组,然后使用max()
获取该广告的最新付款:
SELECT ads.*, max(payments.created)
FROM ads
LEFT JOIN payments ON payments.ads_id=ads.id group by payments.ads_id
答案 1 :(得分:0)
SELECT AD.ID , AD.TITLE, FINAL_PAYMENT.AMOUNT, FINAL_PAYMENT,CREATED
FROM AD
JOIN
( SELECT AD_ID, AMOUNT , CREATED FROM PAYMENT P1
WHERE CREATED = (SELECT MAX(CREATED) FROM PAYMENT P2
WHERE P1.AD_ID = P2.AD_ID
GROUP BY P2.AD_ID
)
) FINAL_PAYMENT
ON
AD.ID = FINAL_PAYMENT.AD_ID
答案 2 :(得分:0)
假设您想同时显示日期和相关金额,一个典型的解决方案(至少在MySQL 8之前)如下所示:
SELECT a.*
, p.amount
, p.created
FROM ads
LEFT
JOIN
( SELECT x.*
FROM payments x
JOIN
( SELECT ads_id, MAX(created) created FROM payments GROUP BY ads_id ) y
ON y.ads_id = x.ads_id
AND y.created = x.created
) p
ON p.ads_id = a.id
或类似的东西