表1: tbl_users :
+----+--------+
| id | name |
+----+--------+
| 1 | waheed |
+----+--------+
| 2 | fareed |
+----+--------+
表2: tbl_watched :
+------------+----+--------+
| id_watched | id | name |
+------------+----+--------+
| 1 | 2 | fareed |
+------------+----+--------+
我想获取总记录,如果tbl_watched不存在,它应该返回zero
或null
输出:
+----+--------+--------+
| id | name |watched |
+----+--------+--------+
| 1 | waheed | 90 |
+----+--------+--------+
| 2 | fareed | null |
+----+--------+--------+
我怎样才能得到这样的结果。?
答案 0 :(得分:2)
使用LEFT JOIN
Select t1.id , t1.name, count(*) as total from tbl_users as t1
left join tbl_watched as t2 on t1.id=t2.id_watched
group by t1.id , t1.name
答案 1 :(得分:1)
您可以使用LEFT JOIN
和users
之间的watched
来实现这一目标。这将保留左表中的所有行,如果右侧没有匹配的记录,则将分配NULL
。在此结果集上,您可以GROUP BY
用户的姓名,并计算每个人看到的内容。
select t1.name, count(t2.id)
from tbl_users t1
left join
tbl_watched t2
on t1.id = t2.watched_id
group by t1.name
答案 2 :(得分:1)
您可以加入表格。我不确定那里的id_watched
列,假设它是来自另一个表的外键。在SqlFiddle为您创建了一个示例模式和查询。请注意,第三人没有任何观看内容,因此在这种情况下,计数将为0。请参阅here。
示例架构:
create table tbl_users (
id INT(8) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(266) NOT NULL
);
create table tbl_movies (
id INT(8) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(266) NOT NULL
);
create table tbl_watched (
id INT(8) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id int(8) UNSIGNED,
movie_id int(8) UNSIGNED,
FOREIGN KEY (user_id) REFERENCES tbl_users(id),
FOREIGN KEY (movie_id) REFERENCES tbl_movies(id)
);
INSERT INTO tbl_users (name) VALUES
("John Doe"),("Jane Doe"),("Jamie Fox");
INSERT INTO tbl_movies (name) VALUES
("The Pianist"),("Django Unchained"),("Pulp Fiction"),("Wanted");
INSERT INTO tbl_watched (user_id,movie_id) VALUES
(1,1),(1,2),(1,3),(2,3),(2,4);
示例查询:
SELECT u.*
, COUNT(w.id) watched_count
FROM tbl_watched w
RIGHT
JOIN tbl_users u
ON u.id = w.user_id
GROUP
BY u.id;