选择查询问题不是我想要的数据

时间:2019-03-13 13:02:59

标签: mysql sql

我有两个表fathergrand_father

CREATE TABLE IF NOT EXISTS father (
    id INT AUTO_INCREMENT,
    father_name VARCHAR(255) NOT NULL,
    PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS grand_father (
    id INT AUTO_INCREMENT,
    father_id int(6) NOT NULL,
    grand_father_name VARCHAR(255) NOT NULL,
    PRIMARY KEY (id)
);
INSERT INTO father (id, father_name) VALUES
  ('1','Abid'),
  ('2','Hasan'),
  ('3','Jabed');
INSERT INTO grand_father (id, father_id,grand_father_name) VALUES
  ('1','1','Jon'),
  ('2','1','James'),
  ('3','2','Jakir'),
  ('4','2','Jamir'),
  ('5','3','Tom');

  select f.father_name,g.grand_father_name
from grand_father g
left join father f
on g.father_id = f.id;

+-------------+-------------------+
| father_name | grand_father_name |
+-------------+-------------------+
| Abid        | Jon               |
| Abid        | James             |
| Hasan       | Jakir             |
| Hasan       | Jamir             |
| Jabed       | Tom               |
+-------------+-------------------+

代码链接:http://sqlfiddle.com/#!9/8be4c/3 查询问题

我想要这样的结果:

+--------------+-------------------+
| father_name  | grand_father_name |
+--------------+-------------------+
|   Abid       | Jon               |
|              | James             |
+--------------+-------------------+
|   Abid       | Jon               |
|              | James             |
+--------------+-------------------+
|   Jabed      | Tom               |
+--------------+-------------------+

有可能吗?
我怎么能得到这样的结果。
我尝试:

select f.father_name, g.grand_father_name 
from grand_father g 
left join father f 
  on g.father_id = f.id

2 个答案:

答案 0 :(得分:1)

使用group_concat()

select f.father_name,group_concat(g.grand_father_name SEPARATOR '\r\n')
from grand_father g
left join father f
on g.father_id = f.id
group by f.father_name

答案 1 :(得分:1)

大概每个人都有一个祖父。在这种情况下:

select f.father_name,
       group_concat(g.grand_father_name) as grand_fathers
from father f join
     grand_father g
     on g.father_id = f.id
group by f.father_name;

我更喜欢默认的逗号分隔,但是您可以更改它。

如果您希望所有父亲,甚至没有祖父的父亲,也可以使用left join