我想根据相同的用户ID值从[listings]
中选择标题列以及列表在[ads]表中的出现次数。
结果应如下所示:
[title] [cnt]
Acme 5
MSFT 10
GOOG 7
等
这不起作用:
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
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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