mysql join 2 table选择一行多行的字段

时间:2013-07-06 12:44:51

标签: mysql codeigniter join

我需要加入两个表格,如下表所示 - 表格2'price_1','price_2'& 'price_3'所以我可以输出价格标签而不是价格值。不确定如何在codeigniter中处理此问题。我是否使用加入当时嵌套的选择?:

表1

id  |   price_1   |   price_2  |  price_3
1   |     6       |      5     |     4

表2

 id | label | value
1   |  £6.50 | 6
2   |  £2.50 | 5
3   |  £4.00 | 4

任何指针都会受到赞赏。

2 个答案:

答案 0 :(得分:0)

您可以先从表1中选择。然后: -

$tags = array();
foreach($record_from_table1 as $record)
{
   $tags[] = $record['price1'];
   $tags[] = $record['price2']; 
   $tags[] = $record['price3'];
}

然后make array_unique($ tags)

从表2中选择查询并获取相应的标签值并回显它们。

答案 1 :(得分:0)

感谢指针,但是基于Codeigniter Join with Multiple Conditions

这样做了
$this->db->select('p1.label as pa_1, p2.label as pa_2, p3.label as pa_3, p4.label as pa_4, p5.label as pa_5');
$this->db->from('table1');
$this->db->join('table2 as p1', 'p1.value = price_1', 'left');
$this->db->join('table2 as p2', 'p2.value = price_2', 'left');
$this->db->join('table2 as p3', 'p3.value = price_3', 'left');
$query = $this->db->get();

谢谢,Dan