在进行查询之前合并两个表?

时间:2011-11-18 14:57:17

标签: mysql date

我正在寻找一种使用2个表进行查询的方法:

posts:
+----+-------------------- +
| ID | post_date           |
+----+---------------------+
| 1  | 2011-11-15 08:42:50 |
+----+---------------------+

meta:
+--------------------+------------+
| post_id | meta_key | meta_value |
+---------+----------+------------+
|    1    |    ip    |192.168.1.10| 
+---------+----------+------------+

所以,我需要查询给定的IP和返回ID,但帖子的日期必须至少10分钟。

这是一个不好的例子:

SELECT ID 
FROM posts
WHERE ip = '192.168.0.1'
   AND post_date = '2011-11-15 08:32:50'

3 个答案:

答案 0 :(得分:4)

SELECT p.ID
    FROM posts p
        INNER JOIN meta m
            ON p.ID = m.post_id
    WHERE m.meta_key = 'ip'
        AND m.meta_value = '192.168.0.1'
        AND p.post_date < DATE_SUB(NOW(), INTERVAL 10 MINUTE)

答案 1 :(得分:4)

SELECT p.ID FROM posts p, meta m 
  WHERE m.post_id=p.ID 
    AND m.meta_value='192.168.0.1' 
    AND p.post_date < (NOW() - INTERVAL 10 MINUTE);

答案 2 :(得分:0)

SELECT p.ID from posts p
INNER JOIN meta m ON (p.ID=m.post_id)

WHERE
m.ip = '192.168.0.1'
   AND
TIMESTAMPDIFF(MINUTE,p.post_date,now()) > 10