我想得到下面用户订阅的帖子数是我的表架构,请帮我查询相同的内容,我有很多选项但是无法做到这一点
我试过并且能够获得以下用户的帖子数量是我的查询,但在这里我使用了静态用户ID,我希望单个查询列出所有用户的计数
SELECT COUNT(*)
FROM CATMAPPING INNER JOIN
POST ON CATMAPPING.pid = POST.id
where FIND_IN_SET(CATMAPPING.cid,(select selectedcatid from subscribers where id='1'));
欲望OP 期望的输出
uemail Postcount
-----------------------------
a@s.com 4
b@s.com 8
c@s.com 10
d@s.com 4
SQL fiddel链接: http://sqlfiddle.com/#!9/4fff8f/2
CREATE TABLE subscribers (
`id` int(10),
`uemail` varchar(255) DEFAULT NULL,
`selectedcatid` varchar(255) DEFAULT NULL
) ;
ALTER TABLE subscribers ADD PRIMARY KEY (`id`);
ALTER TABLE subscribers MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT;
INSERT INTO subscribers (`uemail`, `selectedcatid`) VALUES ('a@s.com', '1'),
('b@s.com', '1,3'),
('c@s.com', '1,2,3'),
('d@s.com', '3');
CREATE TABLE POST (
`id` int(10),
`title` varchar(255) DEFAULT NULL
) ;
INSERT INTO POST (`id`, `title`) VALUES ('1', 'ABC'),
('2', 'DEF'),
('3', 'GHI'),
('4', 'JKL'),
('5', 'MNO'),
('6', 'PQR'),
('7', 'STU'),
('8', 'VXZ'),
('9', 'ASO'),
('10', 'LMO');
CREATE TABLE CATMAPPING (
`cid` int(10),
`pid` int(10) DEFAULT NULL
) ;
INSERT INTO CATMAPPING (`pid`, `cid`) VALUES ('1', '1'),
('2', '2'),
('3', '3'),
('4', '1'),
('5', '2'),
('6', '3'),
('7', '3'),
('8', '3'),
('9', '1'),
('10', '1');
答案 0 :(得分:1)
这是我在sql server中写的正确查询可能是一些语法不同但它给了我正确的结果我创建了一个表值函数然后用它来进行查询。
declare @tempsub as table (subid int,selectcatId int )
insert into @tempsub
select id ,string
from subscribers
CROSS APPLY [dbo].[ufn_CSVToTable] (selectedcatid)
--select * from @tempsub
-- subid is the id of the subscribes table
SELECT subid , count(*) from post p inner join CATMAPPING c on c.pid = p.id
left join @tempsub t on t.selectcatId= c.cid
group by t.subid
-- below is the code for tabled valued function it return a table for comma seprated string
create FUNCTION dbo.[ufn_CSVToTable] ( @StringInput VARCHAR(8000) )
RETURNS @OutputTable TABLE ( [String] nVARCHAR(1000) )
AS
BEGIN
DECLARE @String nVARCHAR(1000)
WHILE LEN(@StringInput) > 0
BEGIN
SET @String = LEFT(@StringInput,
ISNULL(NULLIF(CHARINDEX(',', @StringInput) - 1, -1),
LEN(@StringInput)))
SET @StringInput = SUBSTRING(@StringInput,
ISNULL(NULLIF(CHARINDEX(',', @StringInput), 0),
LEN(@StringInput)) + 1, LEN(@StringInput))
INSERT INTO @OutputTable ( [String] )
VALUES ( @String )
END
RETURN
END