2014-12-18 27 views
0

數據庫結構爲表1如下:加入2個SQL表,分割行到新的列

id | name | total 

樣本數據如下:

1 | Anna | 100,00€ 
2 | Peter | 1000,00€ 
3 | John | 10,00€ 

數據庫結構是如如下表2:

id | code | value 

樣本數據如下:

1 | Tax 24% | 20,00€ 
1 | Tax 14% | 2,00€ 
2 | Tax 24% | 200,00€ 
2 | Tax 14% | 20,00€ 
2 | Tax 24% | 2,40€ 
here might also be sales with 0% and 9% tax 

我多麼希望的sql語句PHP來顯示一個HTML表中的結果:

id | name | Tax with 24% | Tax with 14% | Tax with 9% | total 
* 
1 | Anna | 20,00€ | 2,00 € |  0%  | 100€ 

我怎麼可以這樣寫在MySQL PHP HTML?

<?php $query = $this->db->query("select 
    order_id, 
    firstname, 
    lastname, 
    total, 
    (select value from `" . DB_PREFIX . "order_total` where title='ALV 24%') as tax24, 
    (select value from `" . DB_PREFIX . "order_total` where title='ALV 14%') as tax14, 
    (select value from `" . DB_PREFIX . "order_total` where title='ALV 9%') as tax9 
from 
    `" . DB_PREFIX . "order`"); 

$products = array(); 

// Check if there are any rows returned from the query 
if ($query->num_rows > 0) { 

// Loop through the returned rows for processing 
foreach ($query->rows as $result) { 
    $products[] = array(
     'order_id' => $result['order_id'], 
     'firstname' => $result['firstname'], 
     'lastname' => $result['lastname'], 
     'tax24' => $result['tax24'], 
     'tax14' => $result['tax14'], 
     'tax9' => $result['tax9'], 
     'total' => $result['total'], 
    ); 
} 
} 
foreach ($products as $orders) { ?> 
<table class="list"> 
<tr> 
<td><?php print $orders['order_id']; ?></td> 
<td><?php print $orders['firstname'] . " " . $orders['lastname']; ?></td> 
<td><?php print $orders['tax24']; ?></td> 
<td><?php print $orders['tax14']; ?></td> 
    <td><?php print $orders['tax9']; ?></td> 
    <td><?php print $orders['total']; ?></td> 
</tr> 
<?php 
} 
?>  
</table>  
+0

第二個表中的值表示什麼? – tsnorri

+0

例如,在訂單中支付了24%的稅額 – Christoffer

回答

0

最棘手的部分的僞SQL:

select 
     id, 
     name, 
     (select value from table2 where code='Tax 24%' and table2.id=table1.id) as tax24, 
     (select value from table2 where code='Tax 14%' and table2.id=table1.id) as tax14, 
     (select value from table2 where code='Tax 9%' and table2.id=table1.id) as tax9 
from 
     table1 

當然你必須在php中查詢並正確顯示。

+0

我同意您的意見,這是「正確」的方式。但我不認爲這應該用於生產系統。關係數據庫應該是關係型的,不應該被這種類型的查詢所包含。 –

+0

好吧,代碼被添加到上面,我得到這個錯誤: 致命錯誤:未捕獲異常'ErrorException'帶消息'錯誤:子查詢返回多於一行
錯誤號:1242
select order_id,firstname,lastname,total ,(從'oc_order_total'中選擇value,其中title ='ALV 24%')作爲tax24,(選擇來自'oc_order_total'的值,其中title ='ALV 14%')作爲tax14,(從'oc_order_total'中選擇值,其中title =' ALV 9%')as'tax_9 from'oc_order''in/ – Christoffer

+0

你應該添加類似於子查詢的東西:'和table2.id = table1.id'(我也改變了我的答案,反映了這一點。) –

0

table2.code必須包含像 「24」, 「14」, 「24」 的值..不是 「稅24%」