需要mySql查询

时间:2009-12-27 21:32:50

标签: sql mysql

我有 n 用户数 articleId
如果我通过了 articleId ,我希望得到的结果就像有多少不同的用户查看该文章一样。

Table 1:

recId   userId   articleId    
-----   ------    --------
100      1001      1   
103      178       2   
106      475       3   
107      327       4   
108      567       5   
109      568       6   

Table 2:

userId     jobtitle        articleId
-----       ------          --------  
  327       Engineer          4
  178       Professor         4
  475       Doctors           4
  327       Engineer          5
  568       Student           6
  475       Doctors           4
  475       Doctors           8

如果我将 articleId 作为 4 传递,则应返回详细信息,例如不同用户查看的特定文章的次数,如:

jobtitle   total
-----      ------    
Doctors     2
Engineer    1
Professor   1

如果我将 articleid 传递为 6 ,结果将如下:

jobtitle   total
-----      ------    
Student      1

如何编写这个mysql脚本?

2 个答案:

答案 0 :(得分:3)

select jobtitle, count(articleid)
from table2 
where articleid = YOUR_ARTICLE_ID
group by jobtitle

答案 1 :(得分:2)

SELECT jobtitle, COUNT(*) as count
FROM Table2
WHERE articleId = 4
GROUP BY jobtitle