检查另一个表的MySQL查询

时间:2013-05-30 17:06:33

标签: php mysql

我遇到了两个mysql表的问题。我已经完成了一些代码,我认为我接近解决方案,但我不确定这是否正确。

所以这是两个表:

Table 1: Blogs
Columns: ID, agp_name, agp_url, agp_username, agp_password

Table 2: Keywords
Columns: ID, agp_user_id, agp_order_id, agp_blog_id, agp_keywords, agp_keywords_date

我想要的是根据以下条件从Table1中获取一个随机行:如果agp_keyword与过去5天内的某个关键字匹配,则不包含在结果中。

到目前为止,我做到了这一点:

SELECT 
t1.agp_user_id, t1.agp_order_id, t1.agp_blog_id, t1.agp_keywords, t1.agp_keywords_date, t2.agp_name, t2.agp_url, t2.agp_username, t2.agp_password
FROM table1 AS t1 
INNER JOIN ( 
  SELECT ID, agp_name, agp_url, agp_username, agp_password, agp_blogposts 
  FROM table2 
) AS t2 ON t1.agp_blog_id = t2.ID 
WHERE
  t1.agp_keywords NOT LIKE "%keyword1%" AND 
  t1.agp_keywords NOT LIKE "%keyword2%" AND 
  t1.agp_keywords_date BETWEEN (1369440000 AND 1369932432) 
ORDER BY RAND() LIMIT 1 

但是这不能正常工作。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

试试这个,你的原始规格有点令人困惑:(

SELECT keywords.agp_user_id, 
       keywords.agp_order_id, 
       keywords.agp_blog_id, 
       keywords.agp_keywords, 
       keywords.agp_keywords_date, 
       blogs.agp_name, 
       blogs.agp_url, 
       blogs.agp_username, 
       blogs.agp_password
FROM blogs 
LEFT JOIN keywords
    ON keywords.agp_blog_id = blogs.ID 
        AND keywords.agp_keywords NOT LIKE "%keyword1%" 
        AND keywords.agp_keywords NOT LIKE "%keyword2%" 
        AND FROM_UNIXTIME(keywords.agp_keywords_date) > (DATE_SUB(CURDATE(), INTERVAL 5 DAYS))
ORDER BY RAND() LIMIT 1