2014-12-18 25 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%”