2016-07-30 35 views
2

我有一個表集團通過城市名,只有第一排

city|locality 
a | bc 
a | dc 
a | ef 
a | gh 
a | ij 

我想通過這樣來創建一個組,它顯示

a |bc 
    |dc 
    |ef 
    |gh 
    |ij 

我在一次顯示相同的城市名m目前正在使用

select(*) from 'tablename' group by city; 

但它只給我一個地方值。

+0

不能由SQL – Jens

+0

做真的什麼左加入? –

+0

@ReubenGomes你得到一個完整的行不是空白和值 – Jens

回答

1

不很確定,如果這是你想要的,但如果你想從locality所有行的a在一個新的單元格,可以用這個。

SELECT *, GROUP_CONCAT(locality) as localities FROM table GROUP BY city 

這將輸出:

city localities 
a  bc, dc, ef, gh, ij 
+0

iv treid this但它確實解決了問題..事情是我必須運行一個清理功能來逐行打印我的腳本以獲得loacalities –

+1

爲什麼不通過PHP在你的輸出中解決這個問題? – Perry

+0

是啊,我只是做了這讓它更容易,我只是與價值.....分隔符......分隔符......它只是讓我感到我的數組將看起來像在事件中,我設法得到我想要的東西 –

-1

您可以通過編寫2個查詢嘗試,

select distinct (city) from 'tablename'; 

然後U將得到城市爲 'A';

select * from tablename where city='a';// 'a' means out put of first query 
+0

這真的是效率低下 –

0

試試這個,

select col1, GROUP_CONCAT(col2 SEPARATOR ';') from tablename; 

它會給你喜歡的結果:

一個| bc; dc; ef; gh; ij

現在以您自己的方式使用它。

1

的解決方法就是使用:

select city, locality from yourtable order by city, locality 

然後,您可以只打印/使用city如果值的變化解決的問題在你的表示層。

喜歡的東西(在Java中):

String previousCity = null; 
while (rs.next()) { 
    String currentCity = rs.getString("city"); 
    if (Objects.equals(previousCity, currentCity) { 
     // Same as previous: no need to print so set blank 
     String currentCity = ""; 
    } else { 
     previousCity = currentCity; 
    } 

    System.out.println(currentCity + " | " + rs.getString("locality")); 
}