基本上我想展示来自UserName
的UserEmail
,td_users
以及UserEmail
中没有相同td_add_service
的行。我的表格结构如下
table td_users
id | UserName | UserEmail|
------------------------------
1 | abdul | [email protected]
------------------------------
2 | Rahim | [email protected]
------------------------------
3 | Karim | [email protected]
------------------------------
table td_add_service
---------------------------------------------------
id | serviceName | serviceDeatails | UserEmail|
------------------------------------------------------
1 | Servi1 | testserviceone | [email protected]
--------------------------------------------------------------
2 | Servi11 | testserviceonev | [email protected]
---------------------------------------------------------------
3 | Servi111 | testserviceone1 | [email protected]
---------------------------------------------------------------
4 | Servi111 | testserviceone2 | [email protected]
---------------------------------------------------------------
id是两个表的主键
我想显示数据
---------------------------------------------------
Username | UserMail | No of Services|
------------------------------------------------------
Abdul | [email protected] | 1
------------------------------------------------------
Rahim | [email protected] | 1
---------------------------------------------------
Karim | [email protected] | 2
---------------------------------------------------
我可以从一个表和两个表中检索数据,但不能显示计数数据。
在任何时候使用关系表与int参数但没有nchar例如你的表与电子邮件的关系 - 这是char列
create table #td_users
(id int not null identity(1,1),
usename nchar(10),
email nchar(20)
)
create table #td_add_service
(id int not null identity(1,1),
serviceName nchar(10),
serviceDeatails nchar(20),
UserEmail nchar(20)
)
insert into #td_users(usename,email)
values
('abdul','[email protected]'),
('Rahim ','[email protected]'),
('Karim ','[email protected]');
insert into #td_add_service(serviceName,serviceDeatails,UserEmail)
values
('Servi1','testserviceone','[email protected]'),
('Servi11','testserviceonev','[email protected]'),
('Servi111','testserviceone1','[email protected]'),
('Servi111','testserviceone2','[email protected]');
select tu.usename,
td.UserEmail,
count(td.serviceDeatails) [No of service] from #td_add_service td left join #td_users tu
on td.UserEmail=tu.email
group by tu.usename,td.UserEmail order by 3
usename UserEmail No of service
abdul [email protected] 1
Rahim [email protected] 1
Karim [email protected] 2
SELECT `td_users`.`UserName` AS Username, `td_users`.`UserEmail` AS UserMail, t2.countgroups AS NoOfServices FROM `td_users` LEFT OUTER JOIN (SELECT `id`,COUNT(*) AS countgroups FROM `td_add_service` GROUP BY `UserEmail`) t2 ON `td_users`.`id` = t2.`id`
我想这就是你问的问题。