在2个表

时间:2018-04-26 21:38:16

标签: mysql sql

我的数据库中有2个表格,我想比较每个查询的2个选择查询的值

表1:click_log

查询表1:

SELECT *
FROM click_log

表2:km_articles

查询表2:

SELECT km_article_no
FROM km_articles
WHERE  km_article_date <= "2017-10-31" AND km_article_status = "Published" AND km_article_view_count <= "5"

我要比较的列是表link1clicked for table 1 with km_article_no我知道我会发现重复匹配,然而从那些重复的匹配我想找到我想要从表1中的另一列调用的最新一个&#34; when_clicked&#34;包含数据信息,不确定如何将这些信息放在一起进行查询,然后缩小范围。

这就是表格的样子:

表1:

|link_clicked|when_clicked
     KB00001 | 2017-08-02
     KB00001 | 2017-12-02
     KB00002 | 2017-08-02
     KB00002 | 2017-09-02
     KB00003 | 2017-09-02
     KB00003 | 2017-09-02

表2:

km_article_no|km_article_ti|km_article_status|km_article_view_count|km_article_date
  KB00001    |outlook IOS  |  Published      |         5           | 2017-01-02
  KB00002    |outlook CSS  |  Published      |         4           | 2017-01-05
  KB00003    |outlook ZTE  |   Retired       |         3           | 2017-01-09

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望显示所有km_articles行,每行都包含最新的相关click_log.when_clicked日期。因此,按click_log汇总link_clicked并找到最大值when_clicked。然后将其加入km_articles

select kma.*, cl.last_clicked
from km_articles kma
join
(
  select link_clicked, max(when_clicked) as last_clicked
  from click_log
  group by link_clicked
) cl on cl.link_clicked = kma.km_article_no
where kma.km_article_date <= date '2017-10-31'
  and kma.km_article_status = 'Published'
  and kma.km_article_view_count <= 5;

(如果您还希望在km_articles中显示不匹配的click_log行,请将join更改为left join。)