简体   繁体   English

PHP 连接表 mysql

[英]PHP Join tables mysql

So I have two tables:所以我有两张桌子:

Table1 (sales)表1 (销售额)

  • ID ID
  • Ident标识
  • Date日期
  • Status地位

Table2 (users)表 2 (用户)

  • ID ID
  • Ident标识
  • Fullname全名
  • Email Email

This is how I query the value:这就是我查询值的方式:

<?php      
       $query = "SELECT * FROM sales WHERE status='OK' ORDER BY STR_TO_DATE(`date`, '%Y/%m/%d %H:%i:%s') DESC LIMIT 5";
           if ($result = $link->query($query)) {
                  $num_rows = 0;
                  while ($row = $result->fetch_assoc()) {
                      $num_rows++;
    
                      echo '<div class="my-box">';
                      echo "{$row['id']}";
                      echo "{$row['date']}";
                      echo "{$row['dbirth']}";
                      echo "{$row['email']}";
                      echo "{$row['ident']}";
                      echo '</div>';
                  }
                  $result->free();
              }
          ?>

Right now, it echo the ident for the row, but insted of showing the ident, I was it to display the Fullname that has the ident from Table2.现在,它回ident了该行的标识,但是为了显示标识,我是为了显示具有Fullname标识的全名。 I tried something like SELECT * FROM sales LEFT JOIN users on sales.id = users.id , but that doesn't gives me the Fullname .我尝试了类似SELECT * FROM sales LEFT JOIN users on sales.id = users.id ,但这并没有给我Fullname Any tips?有小费吗?

Your SQL seems wrong.您的 SQL 似乎是错误的。

When you join tables, do this way.当你加入表时,这样做。

SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;

If you join tables right, you will be able to retrieve the 'Fullname' column.如果您正确加入表格,您将能够检索“全名”列。

I believe the Ident field would be the primary key in the users table and foreign key in the sales table.我相信 Ident 字段将是用户表中的主键和销售表中的外键 If yes, this will return the desired result along with other listed fields from both tables.如果是,这将返回所需的结果以及两个表中列出的其他字段。

SELECT sales.ID AS sales_ID,sales.Ident AS Identity,Date,Status,Fullname,Email FROM sales
INNER JOIN users ON sales.Ident = users.Ident
WHERE status='OK'
ORDER BY STR_TO_DATE(`date`, '%Y/%m/%d %H:%i:%s') 
DESC LIMIT 5

If the date field is updated to date or datetime, simply use如果日期字段更新为日期或日期时间,只需使用

ORDER BY DATE

For Better Database practises:为了更好的数据库实践:

  1. You need to change the date field data type to either date or datetime您需要将日期字段数据类型更改为日期日期时间
  2. You need to have an understanding of the Primary and Foreign key concept in RDBMS.您需要了解 RDBMS 中的主键和外键概念。
  3. You need to learn JOINS in SQL你需要在SQL中学习JOINS

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

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