简体   繁体   中英

mysql join 2 table to select one row fields with multiple rows

I need to join two table as follows - table 2 'value' on table 1 'price_1', 'price_2' & 'price_3' so I can output price label instead of the price value. Not sure how approach this in codeigniter. Do I use join the then nested select?:

table 1

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

Table 2

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

Any pointers would be appreciated.

You can first make a select from table 1. Then:-

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

Then make array_unique($tags)

Make select query from table 2 and get corresponding label values and echo them.

thanks for pointers, but did it this way, based on 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();

Thanks, Dan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM