2

我想[listings]根据相同的用户 ID 值从 [ads] 表中选择标题列和列表出现的次数。

结果应如下所示:

[title] [cnt]  
Acme    5  
MSFT    10  
GOOG    7  

ETC

这不起作用:

select 
    l.title,
    (COUNT (id) FROM ads WHERE ads.userid = l.userid) as cnt
from 
    listings l
INNER JOIN 
    ads a on a.userid = l.userid
WHERE 
    l.listingtype = 2
4

3 回答 3

7

我认为查询和其他答案过于复杂

select 
    l.title,
    COUNT (a.id) as cnt
from 
    listings l
INNER JOIN 
    ads a on a.userid = l.userid
WHERE 
    l.listingtype = 2
GROUP BY l.title
于 2013-08-19T08:41:22.113 回答
2

您需要一个group by子句来实现它。

像这样的东西: -

select l.title,COUNT (id) 
(SELECT  COUNT (id) FROM ads WHERE ads.userid=l.userid) as cnt
from listings l
INNER JOIN ads a on a.userid=l.userid
WHERE l.listingtype=2
group by l.title
于 2013-08-19T08:30:51.967 回答
2

你需要SELECT在你的子查询中:

SELECT
    l.title,
    (SELECT COUNT (id) FROM ads WHERE ads.userid = l.userid) AS cnt
FROM 
    listings l
INNER JOIN 
    ads a on a.userid = l.userid
WHERE 
    l.listingtype = 2
于 2013-08-19T08:31:58.817 回答