我有以下mysql tabels
tbl_users
user_id email db_add_date
1 steve@gmail.com 2014-04-22 19:32:35
2 mark@gmail.com 2014-05-02 10:12:01
3 allan@yahoo.com 2014-03-15 05:14:56
4 jim_ross@gmail.com 2014-02-12 14:10:08
tbl_points
id user_id points
1 1 10
2 3 1
3 2 15
4 1 16
5 4 46
6 3 24
我想要获取这些电子邮件&单点
Expected Result
email userid points
mark@gmail.com 2 15
jim_ross@gmail.com 4 46
请帮忙......
更新说明
我想获取点数表中只有1个条目的电子邮件记录
答案 0 :(得分:1)
MySQL 5.5.32架构设置:
create table tbl_users
(
user_id int,
email varchar(20),
db_add_date datetime
);
insert into tbl_users values
(1, 'steve@gmail.com ', '2014-04-22 19:32:35'),
(2, 'mark@gmail.com ', '2014-05-02 10:12:01'),
(3, 'allan@yahoo.com ', '2014-03-15 05:14:56'),
(4, 'jim_ross@gmail.com', '2014-02-12 14:10:08');
create table tbl_points
(
id int,
user_id int,
points int
);
insert into tbl_points values
(1, 1, 10),
(2, 3, 1 ),
(3, 2, 15),
(4, 1, 16),
(5, 4, 46),
(6, 3, 24);
查询1 :
select u.email,
u.user_id,
p.points
from tbl_users as u
inner join (
select user_id,
sum(points) as points
from tbl_points
group by user_id
having count(*) = 1
) as p
on u.user_id = p.user_id
<强> Results 强>:
| EMAIL | USER_ID | POINTS |
|--------------------|---------|--------|
| mark@gmail.com | 2 | 15 |
| jim_ross@gmail.com | 4 | 46 |
答案 1 :(得分:0)
<强> your Expected Result...!!!
强>
(简单和排序查询)
SELECT u.email,u.user_id as userid,p.points
FROM tbl_users u
LEFT JOIN tbl_points p
ON u.user_id = p.user_id
GROUP BY u.user_id
HAVING COUNT(u.user_id) = 1
<强>结果: - 强>
> email userid points
> mark@gmail.com 2 15
> jim_ross@gmail.com 4 46