MySQL:从CROSS JOINed行返回总记录数?

时间:2013-11-17 05:28:11

标签: mysql sql database join cross-join

这是我的SQL小提琴:http://www.sqlfiddle.com/#!2/672f4/1

我正在尝试获取表name中存在的每个pid(技术上,它们的交叉链接info)的记录总数。因此,例如,TOTAL列应为抢劫读取 3 ,为其他所有人读取 1 (jon,tim和BEN)。输出应如下所示:

PID     NAME    TOTAL
1       rob     3
2       jon     1
3       tim     1
4       ben     1

结构:

create table names (
  pid int(10),
  name char(20)
);

insert into names values
    (1, 'rob'),
    (2, 'jon'),
    (3, 'tim'),
    (4, 'ben');

create table info (
  id int(10),
  pid int(10),
  info char(20),
  extra char(10)
);

insert into info values
    (1, 1, 'rob blah', 'heh 1'),
    (2, 2, 'jon blah', 'ha 1'),
    (3, 3, 'tim blah', 'ho 1'),
    (4, 4, 'ben blah', 'hi 1'),
    (5, 1, 'rob blah', 'heh 2'),
    (6, 1, 'rob blah', 'heh 3');

QUERY:

SELECT pid, name, total FROM names CROSS JOIN ( SELECT COUNT(extra) AS total FROM info ) AS total;

非常感谢任何协助。

1 个答案:

答案 0 :(得分:1)

SELECT names.pid, name, COUNT(extra) as total 
FROM names 
LEFT JOIN info 
ON info.pid=names.pid 
GROUP BY names.pid

fiddle