2013-01-15 55 views
1

我想從兩個彼此相鄰的不同表中拉列。提取不同表格中的列並彼此相鄰顯示

我有如下PHP代碼:

<table> 
<tr> 
<th>Date</th> 
<th>Performance A </th> 
<th>Performance B </th> 
</tr> 
$sql = "select date, Aperformance from table1 group by date"; 
$sql1 = "select date, Bperformance from table2 group by date"; 
$result = mssql_query($sql); 
while ($column = mssql_fetch_array($result)) 

{ 
echo "<tr><td>".$column[0]."</td>"; 
echo "<td>".$column[1]."</td></tr>"; 
} 

這如下產生輸出:

Date  | Performance A | Performance B 
01/05/12 | 40%   | 
02/05/12 | 30%   | 
03/05/12 | 25%   | 

現在我要填寫從查詢$ SQL1第三列。我不希望$ sql1的日期列,第二列Bperformance需要放在這裏。我該怎麼做?

+0

FYI:如果查詢不指定' ORDER BY'子句,則不能保證返回的行的順序。並排放置兩個查詢的結果並希望它們有一個共同的列可能會導致驚愕。使用'JOIN'將確保數據相關,但仍然必須指定順序。 – HABO

回答

0

假設兩個查詢返回相同的行數,你可以簡單地做:

$result1 = mssql_query($sql); 
$result2 = mssql_query($sql2); 
while($column1 = mssql_fetch_array($result1)) { 
    $column2 = mssql_fetch_array($result2); 
    echo "<tr><td>$column1[0]</td><td>$column2[0]</td></tr>"; 
} 

如果查詢返回不同大小的結果集,那麼你就必須做一些額外的工作。

+0

感謝它爲我工作... – user1449596

1

你可以簡單地使用連接,使用全外連接,您可以檢索行如果在表中沒有一個匹配日期

SELECT A.Date , A.APerformance AS [Performance A] , B.BPerformance AS [Performance B] 
FROM (
    SELECT Date 
     ,APerformance 
    FROM Table1 
    GROUP BY Date 
    ) A 
FULL OUTER JOIN (
    SELECT Date 
     ,BPerformance 
    FROM Table2 
    GROUP BY Date 
    ) B ON A.Date= B.Date 
+0

@thomas ....感謝這也工作... – user1449596

+0

@ user1449596由於前面的查詢的限制(如marc指出),使用這個更安全。國際海事組織最好在一次查詢呼叫中運行整個事件而不是兩次呼叫 – jazzytomato