I have 2 table in MySQL:
Expected table matches:
id | idA | idB
1 | 21 | 1
2 | 21 | 2
3 | 22 | 3
4 | 8 | 2
5 | 9 | 21
6 | 10 | 7
Table data:
id | projectId | name
1 | 2 | Chicken
2 | 2 | Pork
3 | 2 | Fish
...
21 | 11 | Potato
22 | 11 | Carrot
23 | 11 | Chili
Based on table matches, for example I want to get the name of idA and idB in rows where idA only equals to projectId 11.
I built it in CodeIgniter, I have successfully foreach idA name
, but still failed to get idB name.
I want my view to be like this (using projectId = 11 as an example):
name A | nameB
potato | chicken
potato | Pork
carrot | Fish
However, now I just get
name A | nameB
potato | chicken
potato |
carrot |
Here's my code
Model:
function get_projectA() {
$project_id = $this->uri->segment(4, 0);
$this->db->select('*');
$this->db->from('matches');
$this->db->join('data', 'matches.idA = data.id');
$this->db->where('projectID', $project_id);
$query = $this->db->get();
return $query->result();
}
function get_projectB() {
$project_id = $this->uri->segment(4, 0);
$this->db->select('idB');
$this->db->from('matches');
$this->db->join('image', 'matches.idA = data.id');
$this->db->where('projectID', $project_id);
$query = $this->db->get();
$a = $query->result_array();
foreach ($query->result_array() as $row)
{
$c = $row['idB'];
$query2=$this->db->query("SELECT * FROM data where id='$c'");
$aaa = $query2->result_array();
echo '<pre>';
print_r($aaa);
}
}
VIew:
<tbody id="test">
<?php
foreach($get_projectA as $projectA) {
foreach($get_projectB as $projectB) {
?>
<tr>
<td>
<p><?php echo $projectA->name; ?></p>
</td>
<td>
<p><?php echo $projectB['name']; ?></p>
</td>
<td>
<p>3</p>
</td>
<td>
<p>4</p>
</td>
</tr>
<?php } } ?>
</tbody>
I have no idea what projectid
has to do with this query. But, the following SQL would seem to return what you are looking for:
select tA.name, tB.name
from Expected e join
Table tA
on e.idA = tA.id join
Table tB
on e.idB = tB.id
This actually returns all six rows. The following will limit this to just "project 11":
select tA.name, tB.name
from Expected e join
Table tA
on e.idA = tA.id join
Table tB
on e.idB = tB.id and tB.projectid = 11
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.