2015-12-25 26 views
2

如果可能,我需要在1個查詢中獲取多個信息。從sql中的多個事物中獲取更多字段

比方說,這是該行:

Name - c1 - c2 - c3 - c4 

我需要得到的是在每列的頂部,所以像

Paulus - 50 - 0 - 0 - 0 
John - 0 - 50 - 0 - 0 
Anne - 0 - 0 - 50 - 0 
Chris - 0 - 0 - 0 - 50 

我的查詢應該返回類似:

Paulus - c1(50) - John - c2(50) - Anne - c3 (50),克里斯 - - C4(50) 名稱 - C1 - 名字 - C2

我已經試過:SELECT Name, c1, Name, c2 FROM table ORDER BY c1 DESC, c2 DESC

但它只是不工作,我知道這一切看起來含糊,但我希望有人能夠在這裏理解我的問題...

+2

查看正常化。 – Strawberry

+0

你可以粘貼表格創建代碼嗎?使用'show create table table' – Phiter

+0

@PiterFernandes http://pastebin.com/7XtHUbha這裏是表創建,我需要得到的是從1查詢每列中的頂部'名稱'。我希望你能幫助我... –

回答

0

您可以創建存儲過程或函數並使用while循環,然後在其中創建臨時表並在每個循環中修改您的表並在最後添加新列回答你的答案。

但我建議您使用另一種方式獲取答案並在視圖中進行更改。只需將其改爲展示給最終用戶。

0

你可以用子查詢和一系列自連接來完成。子查詢將返回c1,...,c4列中的最大數字。然後在前面的子查詢中加入表4x以獲取c1,...,c4列匹配最大值的記錄。

然而,請留意@草莓的建議,並規範你的數據結構。

我給你2場的樣本代碼:

select t1.name as maxc1name, m.maxc1, t2.name as maxc2name, m.maxc2 from 
(select max(c1) as maxc1, max(c2) as maxc2 from mytable) m 
inner join mytable t1 on m.maxc1=t1.c1 
inner join mytable t2 on m.maxc2=t2.c2 

美中不足的是:如果在任何列和超過1個記錄從表中相匹配的領帶,會發生什麼任何的最大值。你還沒有定義你想要做什麼,所以我也沒有處理它。

-1

離開模式要求按原樣嘗試:

create table `c_data` (
     `Name` varchar(24) not null, 
     `c1` int(5) not null, 
     `c2` int(5) not null, 
     `c3` int(5) not null, 
     `c4` int(5) not null 
    ); 

    insert c_data values 
     ('Paulus', 50, 50, 0, 0), 
     ('John', 0, 50, 0, 0), 
     ('Anne', 0, 0, 50, 0), 
     ('Chris', 0, 0, 0, 50); 

    select 
     name, 
     case greatest(c1, c2, c3, c4) 
     when c1 then concat('c1', ' (', c1, ')') 
     when c2 then concat('c2', ' (', c2, ')') 
     when c3 then concat('c3', ' (', c3, ')') 
     when c4 then concat('c4', ' (', c4, ')') 
     end as top_column 
    from c_data 
    order by name; 

由於@shadow指出你還必須決定如何處理關係。這個查詢只需要共享最大值的第一列(參見Paulus)。

但是,考慮正如您所建議的正常化您的表。數據將被更有效地存儲,並且該表對於將來的查詢將更加通用。領帶仍然需要處理。該版本從升序字母數字排序中獲取第一個data_type。

create table c_data 
    (
     name varchar(24), 
     data_type varchar(8), 
     data_value int(5) 
    ); 

    insert into c_data values 
    ('Paulus', 'c1', 50), 
    ('Paulus', 'c2', 50), 
    ('John', 'c2', 50), 
    ('Anne', 'c3', 50), 
    ('Chris', 'c4', 50); 

    select 
     name, 
     concat(min(data_type), ' (', max(data_value), ')') as top_column 
    from c_data 
    group by name 
    order by name; 
+0

使用最大()函數的解決方案是不正確的。它將提供記錄中最大的數字,而不是整個數據集。 – Shadow

+0

第二種解決方案也不正確。 – Shadow

+0

我誤解了它,並認爲他們想要每列最大值的列。猜猜一個不太模糊的問題會有幫助。 –

相關問題