繁体   English   中英

在mysql中联接两个表并从第二个表中读取值

[英]Join two tables in mysql and read values from the second table

我想通过将ent表中的att_card_no值与att_user表中的cardno匹配来显示名称。

try {
    $att = $att->query('select att_time,att_date,att_card_no from att_detail WHERE att_card_no IN (select name from att_user where cardno="2342323423")');
    $att -> execute();
    $result = $att -> fetch();
}
catch (PDOException $e){
    echo $att . "<BR>" . $e->getMessage();
}

    $att -> execute();
?>


    <?php echo "Name: ".$result['att_card_no']; ?>



Table:att_detail
+---------+----------+-------------+------------+
| no      | att_time | att_date    | att_card_no|
+---------+----------+-------------+------------+
|       1 | 08:01    | 11-12-17    | 2342323423 |
|       2 | 08:02    | 12-12-17    | 4574574577 |
|       3 | 08:03    | 13-12-17    | 4656456796 |
|       4 | 08:04    | 14-12-17    | 9343450984 |
+---------+----------+-------------+------------+

Table: att_user
+----+-------------+-------------+
| no |    name     |    cardno   |
+----+-------------+-------------+
|  1 | name1       |  2342323423 |
|  2 | name2       |  4574574577 |
|  3 | name3       |  4656456796 |
|  4 | name4       |  9343450984 |
+----+-------------+-------------+

但是不会显示att_user的名称值。 理解这里的错误所在。 也没有错误抛出。

编辑:如果您无法回答它,或者找到解决我问题的类似问题,请让我知道,因为我的搜索没有找到任何东西,但投票否决,这个问题没有帮助

您的SQL语句有几个问题。

由于名称不在选择列的列表中,因此它不会出现在结果集中。 在您所在的位置,您尝试匹配的att_card_no =名称永远不会匹配。

这是您的SQL语句:

select 
    att_time,
    att_date,
    att_card_no 
from att_detail 
WHERE att_card_no IN (select name from att_user where cardno="2342323423")

但这是您真正想要的:

select 
    b.`name`,
    a.`att_time`,
    a.`att_date`,
    a.`att_card_no` 
from ent a 
JOIN att_user b
ON a.`att_card_no` = b.`cardno`;

您需要使用如下的JOIN查询:-

(SELECT att_user.name,att_detail.att_time,att_detail.att_date,att_detail.att_card_no FROM att_user LEFT JOIN att_detail on  att_user.cardno = att_detail.att_card_no WHERE att_user.cardno="2342323423");

注意:-

您查询实际上是这样转换的:

'select att_time,att_date,att_card_no from att_detail WHERE att_card_no IN ("name1")'

因此,基本上没有在此处选择“ name列,并且母鸡不来。

您应该使用JOIN

 $att = $att->query('
    select a.att_time
    , a.att_date
    , a.att_card_no 
    , b.name 
  from att_detail  as a
  inner join att_user as b on a.att_card_no = b.card_no and b.cardno="2342323423"'

暂无
暂无

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

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