简体   繁体   English

如何从表2中选择数据与表1连接

[英]How select data from TABLE 2 join with table 1

How i can to select the user that login for to show name in php, the table 1 is for the main users, and the table 2 is extra users, relationated with main user by ID and ID_ppl 我如何选择要登录的用户以在php中显示名称,表1是主要用户,表2是额外用户,通过ID和ID_ppl与主要用户相关

I need show in php the user name that login. 我需要在php中显示登录的用户名。 but only it show me the main user, Although I login with extra user, And it must show tha name extra user. 但只有它向我显示主要用户,尽管我以其他用户身份登录,并且必须显示名称为其他用户。

For example, i Login with Juana , and in php show me Andres , the main user; 例如,我用Juana登录,并在php中显示主要用户Andres when it must show me Juana name 什么时候必须告诉我胡安娜的名字

Table 1 Main users 表1主要用户

id |  usuario  | password | token | nivel | estado | 
----------------------------------------------------
1  | Andres    | *****    | e12A1 | 1     | on     |
----------------------------------------------------

Table 2 extra users 表2额外用户

id |  usuario  | password | token | id_ppl | nivel | estado |
-------------------------------------------------------------
1  | Juana     | *****    |       | 1      | 2     | on     |
-------------------------------------------------------------
2  | Martin    | *****    |       | 1      | 2     | off    |
-------------------------------------------------------------

Php query php查询

$stmt = $conn->prepare("SELECT T1.id, T1.usuario, T1.token, T1.nivel, T1.estado FROM escolar AS T1 LEFT OUTER JOIN users_extra AS T2 ON T1.id = T2.id_ppl");

    $stmt->bind_param("ss",$usuario, $password); 
     $stmt->execute(); 
     $stmt->store_result(); 
     if($stmt->num_rows > 0){ 
     $stmt->bind_result($id, $usuario, $token, $nivel, $estado);
     $stmt->fetch();

    $user = array(
     'id' => $id,
     'usuario' => $usuario,
     'token' => $token,
     'nivel' => $nivel,
     'estado' => $estado
     );

You're only selecting from T1. 您仅从T1中进行选择。 You need to include the users from T2. 您需要包括T2中的用户。

SELECT T1.*, T2.usuario AS extrausers
FROM escolar AS T1 
LEFT OUTER JOIN users_extra AS T2 ON T1.id = T2.id_ppl

Also, since there are multiple extra users in T2 per user in T1, you'll get multiple rows in your results (one row for each extra user). 同样,由于T1中的每个用户在T2中有多个额外用户,因此您的结果将获得多行(每个额外用户一行)。 You may want to account for that in your php. 您可能需要在您的php中进行说明。

Try this out 试试看

SELECT T1.id, T2.usuario, T1.usuario, T1.token, T1.nivel, T1.estado FROM escolar AS T1 LEFT OUTER JOIN users_extra AS T2 ON T1.id = T2.id_ppl;

Your'e not selecting any column from T2 您没有从T2中选择任何列

Thank you ;) 谢谢 ;)

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

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