简体   繁体   English

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

[英]a field from table A IN a field on table B + mysql + php

I have two tables with the following structure: 我有两个表具有以下结构:

tblA: TBLA:

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

tblB: 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. 我需要从tblA和tblB查询上面的示例,但第二个查询不返回任何记录。

i also tried 'IN' operator but dont worked too... 我也试过'IN'运算符但是也没用过......

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() FIND_IN_SET()vs IN()

You can use a different approach by extracting each of the ids from aid column separately 您可以通过分别从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
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM