从3个表中获取最后的记录

时间:2018-06-12 06:50:32

标签: php mysql

My tables

    $sql="SELECT *
          FROM addresses
          LEFT JOIN users ON address_id = user_id
          LEFT JOIN notes ON note_id = user_id
          ORDER BY id DESC
          LIMIT 1";

这是我的SQL查询,我的任务是显示3个表中的最后一条记录,但表格是空白的,我不知道为什么,提前感谢人们:)

3 个答案:

答案 0 :(得分:0)

我猜问题来自 ORDER BY id DESC 。 实际上,你没有所谓的id列。 您应该删除此子句,以使代码正常工作。

如果你想取最后的记录,你可以放一个 ORDER BY address_id DESC 来完成这项工作!

直接编辑的代码:

      $sql="SELECT *
      FROM addresses
      LEFT JOIN users ON address_id = user_id
      LEFT JOIN notes ON note_id = user_id
      ORDER BY adress_id DESC
      LIMIT 1";

答案 1 :(得分:0)

这可能有效:

SELECT a.address_id, u.user_id, n.note_id
FROM addresses a
LEFT JOIN users_addresses ua ON ua.ua_address_id = a.address_id
LEFT JOIN users u ON u.user_id = ua.ua_user_id
LEFT JOIN notes n ON n.note_user_id = u.user_id
ORDER BY a.address_id DESC
LIMIT 1

答案 2 :(得分:0)

这是从所有表中获取所有数据的查询,不确定你的意思是3个表的最后记录是什么,我可以在那里看到四个表:

SELECT *
FROM `addresses`
LEFT JOIN `users_addresses` ON `users_addresses`.`ua_address_id` = `addresses`.`address_id`
LEFT JOIN `users` ON `users`.`user_id` = `users_addresses`.`ua_user_id`
LEFT JOIN `notes` ON `notes`.`note_user_id` = `users`.`user_id`;