2017-07-30 73 views
2

我想通过将ent表中的att_card_no的值与att_user表中的cardno进行匹配来显示名称。在mysql中加入两个表并从第二个表读取值

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的名称值。感谢您了解这里出了什么问题。也没有错误抛出。

编辑:如果你不能回答这个问题,或者如果您发现类似Q,解决了我的问题,请让我知道,因为我的搜索没有找到任何而是反对投票这个问题是没有帮助一点

+0

为什么要“名”显示,如果你不选择它?你为什么认为“att_card_no”在“select name ...”中? –

+0

@ MichaelO.如果您滚动浏览,则可以看到我确实在第二个表att_user中选择了它。检查表 – X10nD

+0

'WHERE att_card_no IN(select name'没有意义,因为'att_card_no'是一个包含数字的列,'name'是一个包含字符串的列 –

回答

1

您需要使用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列在那里被选中,并且母鸡没有来。

+0

它的工作.... 你能告诉我什么是我的sql语句错误,它没有工作吗 – X10nD

+0

所以现在它的工作? –

+0

是的,但为什么没有我的声明没有工作? – X10nD

1

你应该使用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"' 
2

有几个问题与你的SQL语句。

由于名称不在select的列表列表中,因此它不会出现在结果集 中。在你的地方,你正试图匹配att_card_no = name,这不会有 的匹配。

这是你的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`;