简体   繁体   中英

MySQL query that checks in another table

I've got a problem with two mysql tables. I've done some code and I think I am close to the solution, but I'm not sure if this is right.

So here are the two tables:

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

What I want is to get one random row from Table1 based on the following condition: if the agp_keyword match one of the keywords in the last 5 days then do not include into the result.

So far I did this:

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 

However this does not work correctly. Any help will be appreciated.

Try this, your original specifications were a bit confusing :(

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM