我有两张表,结构如下:
TBLA:

+----------+---------------+
| id (int) | name (string) |
+----------+---------------+
|        1 | a             |
|        2 | b             |
|        3 | c             |
+----------+---------------+

tblB:

+----------+---------------+-------------+
| id (int) | name (string) | aid(string) |
+----------+---------------+-------------+
|        1 | x             | '1,2'       |
|        2 | y             | '2,'        |
|        3 | z             | '1,3'       |
+----------+---------------+-------------+
$a = $this::$db->prepare('SELECT * FROM tblB WHERE id= :id LIMIT 1');
$a->bindValue(':id', $ID, PDO::PARAM_INT);
$a->execute();
$r = $a->fetch(pdo::FETCH_ASSOC);

if ($a->rowCount() > 0){
    $bInf = $r['id']   . '|*|' .
            $r['name'] . '|*|' .
            $r['aid']  . '|**|';

    $b = $this::$db->prepare('SELECT id,name FROM tblA WHERE FIND_IN_SET(id,:ids)');
    $b->bindValue(':ids', $r['aid']);
    $b->execute();
    $rs = $b->fetchAll(pdo::FETCH_ASSOC);

    if ($b->rowCount() > 0)
    {
        foreach ($rs as $srow => $srval)
          $aInf .= $srval['id']   . '[|]' .
                   $srval['name'] . '[#]' ;
    } else
        $aInf = ' ';
        $aInf.=  '|***|' . $bInf;
    }
}

我需要从TBLA和TBLB查询上述示例,但第二个查询不返回任何记录。
我也试过“进去”接线员,但也没工作…
请帮我…

最佳答案

通过分别从aid列提取每个id,可以使用不同的方法

$a = $this::$db->prepare('SELECT * FROM tblB WHERE id= :id LIMIT 1');
$a->bindValue(':id', $ID, PDO::PARAM_INT);
$a->execute();
$r = $a->fetch(pdo::FETCH_ASSOC);

if ($a->rowCount() > 0)
{
    $bInf = $r['id']   . '|*|' .
            $r['name'] . '|*|' .
            $r['aid']  . '|**|';

    //extract each of the ids in the variable 'aid'
    $tbla_ids = explode(',',$r['aid']);
    foreach($tbla_ids as $tbla_id){
        //case for the record where aid = '2,'
        if(strlen($tbla_id)==0){
            continue;
        }
        $b = $this::$db->prepare('SELECT id,name FROM tblA WHERE id= :ids');
        $b->bindValue(':ids', $tbla_id);
        $b->execute();
        //do what you need to do here. The query returns the single record
        //from tbla that matches the id $tbla_id
    }
}

10-06 01:49