开发者

finding latest entry in DB and all other before it in a different table

开发者 https://www.devze.com 2023-04-12 18:00 出处:网络
This is a fairly easy thing in theory but i havent got a clue how to do it. What i need is a method to find the latest timestamp/entry in a table called \'answers\' in an MySQL DB. And upon finding th

This is a fairly easy thing in theory but i havent got a clue how to do it. What i need is a method to find the latest timestamp/entry in a table called 'answers' in an MySQL DB. And upon finding this, to find all IP's stored in a table called 'ip' by timestamp that occur before the said mention 'answers' entry.

Any ideas? Im guessing an if() function would be the best way?

Edit: table structure where 'ip' exists.

CREATE TABLE IF NOT EXISTS `votes` (
`id` int(250) NOT NULL AUTO_INCREMENT,
`ip` varchar(30) NOT NULL,
`answer_id` int(250) NOT NULL,
`poll_id` int(250) NOT NULL,
`timestamp` int(250) NOT NULL, PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

And the table where the 'answers' live

CREATE TABLE IF NOT EXISTS `answers` (
`id` int(250) NOT NULL AUTO_INCREMENT,
`poll_id` in开发者_运维技巧t(250) NOT NULL,
`answer` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;


Surely this can be a pure database solution an doesn't need anything doing in PHP?

Assuming the tables are in the same database, both have a timestamp column and are named answers and votes respectively, then:

SELECT * FROM votes v
WHERE v.timestamp <= (SELECT max(a.timestamp) FROM answers a)

EDIT : Replaced names according to your schema, but I don't see a timestamp column in answers?


select * from ip x where x.timestamp <= (select max(y.timestamp) from answer y)


To get the latest timestamp you can use...

SELECT timestamp_field FROM answers ORDER BY timestamp_field DESC LIMIT 1

Then run a second query matching the result from that query.

0

精彩评论

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

关注公众号