【问题标题】:mysql join 2 table to select one row fields with multiple rowsmysql join 2 table to select one row fields with multiple rows
【发布时间】:2013-07-06 12:44:50
【问题描述】:

我需要按如下方式连接两个表 - 表 1 'price_1'、'price_2' 和 'price_3' 上的表 2 'value',这样我就可以输出价格标签而不是价格值。不知道如何在 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

任何指针将不胜感激。

【问题讨论】:

  • label 并没有真正的“£”符号,是吗?并考虑规范化您的数据 - table1 (id, price_id, price)
  • label 中确实包含“£”,因为它是文本,仅用于显示价格。价格“代码”是 price_1price_2price_3 中的值,这些是我需要在表 2 中与 value 连接的值。这些是我用于其他目的的现有表,所以更喜欢不要更改它们,还有另一个与表 1 行关联的 id,但为简单起见,我没有将其包含在此处。

标签: mysql codeigniter join


【解决方案1】:

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

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

然后制作array_unique($tags)

从表2中进行选择查询,得到对应的标签值并回显。

【讨论】:

  • 他想加入price_1price_2price_3,而不是id
【解决方案2】:

感谢指点,但这样做是基于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();

谢谢,丹

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 2015-10-05
    • 1970-01-01
    • 2010-09-23
    • 2014-10-26
    • 1970-01-01
    • 2022-10-06
    • 2013-10-25
    • 1970-01-01
    相关资源
    最近更新 更多