表A中的字段表B上的字段+ mysql + php

时间:2015-09-14 23:38:03

标签: php mysql sql pdo

我有两个具有以下结构的表:

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查询上面的示例,但第二个查询不会返回任何记录。

我也尝试过“IN”操作符,但也没用过......

请帮助我...

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

ball.physicsBody?.restitution = 0.9

有关详细信息,请参阅:

FIND_IN_SET() vs IN()

答案 1 :(得分:1)

您可以通过分别从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
    }
}

答案 2 :(得分:0)

我犯了一个有趣的错误,通过删除“字符来自”援助“字段,问题解决了,FIND_IN_SET现在正常工作。