加入mysql的两个查询

时间:2017-07-06 19:00:47

标签: mysql

我想加入两个问题:

第一个查询获取“pgm_posts.post_title”和“pgm_post_views.count”(WHERE pgm_post_views.type =“4”)

pgm_posts TABLE

SELECT pgm_posts.post_title, pgm_post_views.count
FROM pgm_posts, pgm_post_views
WHERE  pgm_post_views.type="4" AND pgm_post_views.id = pgm_posts.id

第二个查询从条件中获取“pgm_post_views”中的所有ID。

pgm_post_views.type =“0”:获取“期间”的条件。 (看img)

pgm_post_views TABLE

SELECT pgm_posts.id
FROM pgm_posts
INNER JOIN pgm_post_views
ON pgm_posts.id = pgm_post_views.id AND pgm_post_views.type="0" AND DATE_FORMAT(pgm_post_views.period, "%Y-%m-%d") <= DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-%d') AND DATE_FORMAT(pgm_posts.post_date, "%Y-%m-%d") <= DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-%d')

恢复:首先查询根据第二个查询的所有ID获取post_title和总计数。

我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

一种简单的方法是基于所选表格的纯连接

SELECT p
        gm_posts.post_title
      , pgm_post_views.count
FROM pgm_posts 
INNER JOIN  pgm_post_views ON  pgm_post_views.id = pgm_posts.id 
                  AND pgm_post_views.type="4"
INNER JOIN ( 
 SELECT 
        pgm_posts.id
 FROM pgm_posts
 INNER JOIN pgm_post_views ON pgm_posts.id = pgm_post_views.id AND pgm_post_views.type="0" 
          AND DATE_FORMAT(pgm_post_views.period, "%Y-%m-%d") <= 
                        DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-%d') 
          AND DATE_FORMAT(pgm_posts.post_date, "%Y-%m-%d") <= 
                        DATE_FORMAT(CURRENT_DATE - INTERVAL 1 MONTH, '%Y-%m-%d')
) T on T.id = pgm_posts