简体   繁体   中英

a field from table A IN a field on table B + mysql + php

I have two tables with the following structure:

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

i need to query from tblA and tblB as above sample, but second query dont return any records.

i also tried 'IN' operator but dont worked too...

pls help me...

Try something like this:

SELECT * FROM tblb,tbla
WHERE tblb.id= 1 AND FIND_IN_SET(tbla.id, tblb.aid)

for details, refer to:

FIND_IN_SET() vs IN()

You can use a different approach by extracting each of the ids from aid column separately

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

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

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