2012-09-20 121 views
4

如何編寫一個MySQL查詢來實現這個任務?MySQL只計算新記錄

表:作家

w_id w_name 
--------------- 
    1  Michael 
    2  Samantha 
    3  John 
--------------- 

表:文章

a_id w_id timestamp a_name 
---------------------------------------- 
    1  1  1  PHP programming 
    2  3  3  Other programming languages 
    3  3  5  Another article 
    4  2  15  Web design 
    5  1  20  MySQL 
---------------------------------------- 

需要COUNT只有那些作家誰發表了他們的第一篇文章不早於。
(僅誰發表至少一篇文章可以算作作家)


在這個例子中,結果將是: (一個作家 - 薩曼莎)

SQL代碼進行測試in this SQLFiddle

回答

3

您需要的雙重選擇。

首先,你取w_id,加上第一篇文章的時間戳:

SELECT w_id, MIN(timestamp) as publish FROM articles GROUP BY w_id 

然後你要求publish不早於5:

SELECT w_id, MIN(timestamp) as publish 
    FROM articles 
    GROUP BY w_id 
    HAVING publish >= 5; 

然後你加入這個 「表」 與writers如果你願意,可以得到這個名字。

但如果你只想計數,你不需要writers表都:

SELECT COUNT(*) AS answer FROM 
    (SELECT w_id, MIN(timestamp) AS publish 
     FROM articles 
     GROUP BY w_id 
     HAVING publish >= 5 
) AS counter; 

測試:http://sqlfiddle.com/#!2/0e90f/30/0

2

你需要有一個子查詢得到作家的最低timestamp。結果將被計入sinceyou不能聚集一列,它是已經彙總(例如)。 COUNT(MIN(列名))

SELECT COUNT(*) totalWriters 
FROM 
(
    SELECT a.w_id, MIN(b.`timestamp`) 
    FROM writers a 
      INNER JOIN articles b 
      ON a.w_id = b.w_id 
    GROUP BY a.w_id 
    HAVING MIN(b.`timestamp`) >= 5 
) a 

SQLFiddle Demo

1

一個簡單的方法:

SELECT COUNT(DISTINCT w_id) 
FROM writers 
WHERE w_id NOT IN 
(SELECT w_id from articles 
WHERE timestamp <=5) 
1
select count(*) 
from (
    select w_id, min(`timestamp`) as `timestamp` 
    from articles 
    group by w_id 
) s 
where `timestamp` >= 5 
1
select count(1) from (
    select w.w_id, count(a.timestamp) cnt from writers w 
    inner join articles a on a.w_id = w.w_id 
    group by w.w_id 
) t 
inner join articles art on art.w_id = t.w_id 
where t.cnt = 1 and art.timestamp > 5 
1

試試這個,我哈剛纔已經測試..

select* from (select tblw.w_id, count(tblart.timestamp) count from writers tblw inner join articles tblart on tblart.w_id = tblw.w_id group by tblw.w_id) temp inner join articles art on art.w_id = temp .w_id where temp .count = 1 and art.timestamp > 5 
2

這很容易,這裏是查詢:

SELECT count(DISTINCT w_id) 
FROM articles 
WHERE TIMESTAMP>=5 
AND w_id NOT IN (SELECT w_id FROM articles WHERE TIMESTAMP<5); 

SQL Fiddle