我在MySQL中有2个表:

预期的表格匹配项:

id | idA | idB

1  | 21  | 1
2  | 21  | 2
3  | 22  | 3
4  | 8   | 2
5  | 9   | 21
6  | 10  | 7


表格数据:

id | projectId | name
1  |    2      | Chicken
2  |    2      | Pork
3  |    2      | Fish
...
21  |   11     | Potato
22  |   11     | Carrot
23  |   11     | Chili


例如,基于表匹配,我想在idA仅等于projectId 11的行中获取idA和idB的名称。

我在CodeIgniter中构建了它,我已经成功foreach idA name,但是仍然无法获得idB名称。

我希望我的视图是这样的(以projectId = 11为例):

name A  | nameB
potato  | chicken
potato  | Pork
carrot  | Fish


但是,现在我得到了

name A  | nameB
potato  | chicken
potato  |
carrot  |


这是我的代码

模型:

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);
    }
}


视图:

<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>

最佳答案

我不知道projectid与该查询有什么关系。但是,以下SQL似乎会返回您要查找的内容:

select tA.name, tB.name
from Expected e join
     Table tA
     on e.idA = tA.id join
     Table tB
     on e.idB = tB.id


实际上,这将返回所有六行。下面将限制为“项目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

10-08 00:52