2012-05-18 112 views
3

我得到了2個表,table1 & table2。SQL查詢,我需要一些值

table1的字段有:

id 
atype 
adesc 
aid 

表2字段有:

id 
aid 
adesc 
value_1 
value_2 


$query1 = mysql_query("Select DISTINCT atype from table1"); 
while($row = mysql_fetch_array($query1)){ 
    $atype = $row['atype']; 
    $query2 = mysql_query("Select adesc from table1 where atype='$atype' and aid IN (Select aid from table2) order by id asc"); 
    while($row2 = mysql_fetch_array($query2)){ 
     // i know query2 can only get adesc, so i need value_1 and value_2 in this 
     echo $row2['adesc'] .'>> '. (this should be value1 from table2) .'>> '. (this should be value2 from table2); 
    } 
} 


我想要得到的value_1value_2。任何幫助,將不勝感激。




編輯:
table1的值是在我的數據庫(atype的,援助,adesc分別):在我的表2

type1 111 'this is type 1' 
type1 111 'this is type 1' 
type2 112 'this is type 2' 
type3 113 'this is type 3' 
type4 114 'this is type 4' 
type1 111 'this is type 1' 
type4 114 'this is type 4' 
type2 112 'this is type 2' 

值(援助,adesc,VAL1, val2,分別):

111 'this is type 1' 100 50 
111 'this is type 1' 100 50 
112 'this is type 2' 300 500 
113 'this is type 3' 100 50 
112 'this is type 2' 100 50 
114 'this is type 4' 100 50 
111 'this is type 1' 100 50 

我在說什麼盟友希望工程是這樣的:

type1 
     (sum)value_1 (sum)value_2 
type2 
     (sum)value_1 (sum)value_2 
type3 
     (sum)value_1 (sum)value_2 
type4 
     (sum)value_1 (sum)value_2 
+1

我真的希望'$ atype'是從不使用 「翡翠的類型」'。 – tadman

回答

1
$query2 = mysql_query("Select t1.adesc, t2.value_1, t2.value_2 from table1 as t1, table2 as t2 where t1.atype='$atype' and t1.aid = t2.aid order by t1.id asc"); 

    while($row2 = mysql_fetch_array($query2)){ 
     // i know query2 can only get adesc, so i need value_1 and value_2 in this 
     echo $row2['adesc'] .'>> '. $row2['value_1'] .'>> '. $row2['value_2']; 
    } 

UPD:

$sql = <<<SQL 
select t1.adesc, sum(t2.value_1) as v1, sum(t2.value_2) as v2 
from 
table1 as t1, 
table2 as t2 

where 
t1.aid = t2.aid 
group by t1.atype 

order by t1.atype asc 
SQL; 
$query = mysql_query($sql); 
while($row = mysql_fetch_array($query2)){ 
    // i know query2 can only get adesc, so i need value_1 and value_2 in this 
     echo $row['adesc'] .'>> '. $row['v1'] .'>> '. $row['v2']; 
} 
+0

thx爲迴應.. imma試試這個。 –

+0

這解決了我的問題。 thx很多謝爾蓋。 –

+0

顯然他們不在我應該如何顯示它。請查看我的編輯信息瞭解詳情。 –

-1

此SQL查詢應該產生你想要的結果:在SQL

select adesc, 
     value_1, 
     value_2 

from table1 

where atype='$atype' and 
     aid IN (Select aid from table2) 

order by id asc 
+0

value_1,表2中的value_2 – Sergey

0

使用一個簡單的innerjoin,而不是你的兩個選擇:

select table1.adesc,atable2.value1 from table1,table2 where table2.adesc=table1.adesc and table1.aid=table2.aid order by table1.aid asc 

編輯:

select table1.adesc,atable2.value1 from table1,table2 where table1.aid=table2.aid order by table1.aid asc 
+0

就是這樣 - Connor基於innerjoin編寫了整個代碼。 – int2000

+0

「table2.adesc = table1.adesc」在源代碼 – Sergey

+0

thx中沒有指定這個條件。imma試試這個。 –