Mysql SQL-最接近Now()的行,但唯一
所以我有一个小问题。我有两个表,一个包含商户信息、名称等,另一个包含事件Mysql SQL-最接近Now()的行,但唯一,mysql,sql,Mysql,Sql,所以我有一个小问题。我有两个表,一个包含商户信息、名称等,另一个包含事件 我每隔几天上传一次价格到事件表,因此有很多重复内容只能通过时间戳列(Uploaddate)来区分 我需要选择最新上传的价格,因此其他不被选择 即,选择最新的价格,并确保每个商户都是唯一的,因此每个商户只有一个价格 以下是我到目前为止的情况: SELECT * FROM wp_events, wp_merchants WHERE DATE = '2012-02-26' AND eventname = 'testevent
SELECT *
FROM wp_events, wp_merchants
WHERE DATE = '2012-02-26'
AND eventname = 'testevent'
AND `uploaddate` > NOW( )
AND wp_events.merchant = wp_merchants.merchant_name
ORDER BY uploaddate DESC
在子查询中使用MAX()
SELECT
MAX(DATE), event, merchant
FROM
someTable
GROUP BY
event, merchant
接下来,将子查询合并到主查询中以获得最新的价格(我想这就是您想要的):
我还没有验证代码。试试看:
select e1.merchant, e1.price from event e1
left join event e2
on (e1.merchant = e2.merchant and e1.date < e2.date)
where e2.merchant is null
因此,您必须添加所需的联接和筛选器
编辑:
这不是你要找的吗
select e1.merchant, e1.price from wp_events e1
left join wp_events e2
on (e1.merchant = e2.merchant and e1.uploaddate < e2.uploaddate)
where e2.merchant is null
从wp_事件e1中选择e1.merchant、e1.price
左连接wp_事件e2
on(e1.merchant=e2.merchant和e1.uploaddate
您使用的是什么rdbms?另外,如果您正在查找uploaddate>now(),这似乎是在将来查找记录,我认为您不会有上载日期大于当前日期的记录。您好,是的,我已将uploaddate>now()更改为uploaddateselect e1.merchant, e1.price from event e1
left join event e2
on (e1.merchant = e2.merchant and e1.date < e2.date)
where e2.merchant is null
+----------+-------+
| MERCHANT | PRICE |
+----------+-------+
| ShopY | £11 |
| ShopX | £9 |
+----------+-------+
select e1.merchant, e1.price from wp_events e1
left join wp_events e2
on (e1.merchant = e2.merchant and e1.uploaddate < e2.uploaddate)
where e2.merchant is null