SQL - 获取特定列中包含数据的最新行,或者如果该列中没有数据则仅获取最新行
我有一个记录地址更新历史的表,称为交易。模式类似于 row_id (int, PK)、user_id (int)、address1 (varchar)、transdate (timestamp)。
我想查询表并为用户返回一行,显示最新行(即最大时间戳),但如果 address1 列中有数据,我想要包含数据的最新行。如果此列中没有数据,则仅显示最新行。
示例:
row_id user_id address1 transdate 1 70005 56 The Street 2010-08-25 09:15 2 70005 NULL 2010-08-25 10:04 3 70005 12 Some Road 2010-08-25 11:17 4 70005 NULL 2010-08-25 12:18
查询
SELECT user_id, address1 FROM transaction t WHERE user_id = 70005 AND row_id = (SELECT MAX(row_id) FROM transaction ti WHERE ti.user_id = t.user_id)
对于像返回结果这样的
user_id address1 70005 NULL
,但我想要的是
user_id address1 70005 12 Some Road
因为这是具有一些数据的该用户的最新行。
希望这是有道理的。有人有什么建议吗?
我正在使用 MySQL 5.1.49(社区)。谢谢。
I have a table that records a history of address updates, called transaction. The schema is something like row_id (int, PK), user_id (int), address1 (varchar), transdate (timestamp).
I want to query the table and have a single row returned for a user showing what is the latest row (i.e. greatest timestamp), but if there is data in the address1 column I want the latest row with data. If there is no data in this column then just the latest row.
Example:
row_id user_id address1 transdate 1 70005 56 The Street 2010-08-25 09:15 2 70005 NULL 2010-08-25 10:04 3 70005 12 Some Road 2010-08-25 11:17 4 70005 NULL 2010-08-25 12:18
With a query like
SELECT user_id, address1 FROM transaction t WHERE user_id = 70005 AND row_id = (SELECT MAX(row_id) FROM transaction ti WHERE ti.user_id = t.user_id)
the returned result would be
user_id address1 70005 NULL
but what I want is
user_id address1 70005 12 Some Road
because this is the latest row for that user that has some data.
Hope this makes sense. Does anyone have any suggestions?
I am using MySQL 5.1.49 (community). Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该优先考虑包含数据的行,同时在
address1
为NULL
时仍然有效。我还会使用transdate
而不是row_id
。This should prioritize rows with data, while still working when
address1
isNULL
. I would also usetransdate
instead ofrow_id
.已更新
UPDATED
看看这个问题的接受答案(不是我的答案,他的答案)更好)
通过将结果与地址进行并集,然后将没有地址的结果进行并集,您可以确定优先级并仍然使用简单的子查询连接。
请注意,您获取的是最大 row_id,而不是最大日期,因此即使您这样做,您也不会获得预期的结果。
Take a look at the accepted answer on this question (not my answer, his was better)
By doing a union of the results with address and then the results where there is no address, you can prioritize and still use a simple subquery join.
Note that you're grabbing the max row_id, not that max date, so you're not going to get the results you expect, even if you do this.