开发者

Select results based on Date but knowing the ID

This is table History:

URL | UID | Method | Tag | Date

And this query:

$data = mysql_query("
        select * from History 
        order by `Date` asc         
        "); 

I need to get the URLs that have an older Date than a record.

I only have the URL of this record. ($url)

Is there is a way to find it and selec开发者_运维知识库t rows that come before in the order by date?

I can run a separate query with the $url to get it's Date but I want to know if it's possible to do it with one query.


You can use a subselect:

SELECT *
FROM History
WHERE Date < (SELECT Date FROM History WHERE url = 'foo')
ORDER BY Date ASC 

Add a unique index to url to ensure that the subquery will only return one record.


This is a better performance then sub-selects:

SELECT
  h1.*
FROM
  history h1
INNER JOIN 
  history h2 
ON
  h2.url = '{URL}'
WHERE
  DATEDIFF(h1.`date`,h2.`date`) < 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜