2015-07-11 167 views
1

我有以下3個重複的id表我想從相同的id中檢索具有不同名稱和日期的記錄,我需要查詢以獲得預期的結果輸出。從3個表中選擇不同列的公共記錄

CREATE TABLE Student1 
    (`id` int,`status` int,`amount` int , `Name` varchar(10), `date` varchar(55)) 
; 
    INSERT INTO Student1 
    (`id`,`status`,`amount`, `Name`, `date`) 
VALUES 
    (1,0,4500, 'ram', '04/02/2012'), 
    (2,0,2000, 'shyam', '05/09/2013'), 

    (4,0,1500, 'ghanshyam', '08/11/2014') 
; 


CREATE TABLE Student2 
    (`id` int,`status` int,`amount` int , `Name` varchar(10), `date` varchar(55)) 
; 

INSERT INTO Student2 
    (`id`,`status`,`amount`, `Name`, `date`) 
VALUES 

    (3,0,4500, 'gopal', '04/02/2012'), 
    (2,0,8000, 'radheshyam', '15/11/2013'), 
    (4,1,1500, 'ghanshyam', '18/10/2015') 
; 

CREATE TABLE Student3 
    (`id` int,`status` int,`amount` int , `Name` varchar(10), `date` varchar(55)) 
; 

INSERT INTO Student3 
    (`id`,`status`,`amount`, `Name`, `date`) 
VALUES 

    (1,1,4500, 'ram', '14/02/2012'), 
    (2,0,6500, 'radhe', '11/11/2014'), 
    (3,1,4500, 'gopal', '14/02/2015') 
; 

除外結果:

id status amount  Name  date 
    2 0  2000  shyam  05/09/2013 
    2 0  6500  radhe  11/11/2014 
    2 0  8000 radheshyam 15/11/2013 
+0

它通常是一個糟糕的設計具有相同的列三個表。您應該將它們放在同一個表格中,列中指定「1」,「2」或「3」。 –

回答

1

你只需要使用union all帶來的表一起。一種方法是:

select s.* 
from (select s.* from student1 s union all 
     select s.* from student2 s union all 
     select s.* from student3 s 
    ) s 
where id = 2; 

正如我在評論中所說的,通常你會有三張表而不是一張。

我意識到我可能誤解了這個問題。如果你想找到記錄具有相同的ID,但不同的名字,然後使用:

select s.id, group_concat(s.name) as names 
from (select s.* from student1 s union all 
     select s.* from student2 s union all 
     select s.* from student3 s 
    ) s 
group by s.id 
having count(distinct name) = 3 -- or perhaps >= 2, depending on what you mean 

如果你想完整記錄,你可以加入此回原來的表。

編輯:

如果你想所有原始行:

select s.* 
from (select s.id, group_concat(s.name) as names 
     from (select s.* from student1 s union all 
      select s.* from student2 s union all 
      select s.* from student3 s 
      ) s 
     group by s.id 
     having count(distinct name) = 3 
    ) ss join 
    (select s.* from student1 s union all 
     select s.* from student2 s union all 
     select s.* from student3 s 
    ) s 
    on ss.id = s.id; 
+0

我想檢索完整的記錄,那麼請問如何查詢 –

+0

我只需要具有相同ID但不同名稱和不同日期的完整記錄。 –

+0

@ Gordan Linoff,它展示了未知桌子的' –

相關問題