MySQL的。从第二个表中选择最后一条记录(按创建时间)

时间:2015-10-26 14:50:20

标签: php mysql

我有userPhone的2个表格链接。

用户

+-----------+-------+----------+--------+
| userPhone |  name | address  |  car   |
+-----------+-------+----------+--------+
| 096111111 | Bill  |  adr1    | {json} |
+-----------+-------+----------+--------+
| 097333333 | Max   |  adr2    | {json} |
+-----------+-------+----------+--------+
| 098888888 | Denis |  adr3    | {json} |
+-----------+-------+----------+--------+

订单

+-----------+---------+-------+-------+------------+
| userPhone | orderID | title | Descr | createdTS  |
+-----------+---------+-------+-------+------------+
| 096111111 | 59      | ttl1  | qqqq  | 1444999740 |
+-----------+---------+-------+-------+------------+
| 096111111 | 58      | ttl2  | wwww  | 1444999650 |
+-----------+---------+-------+-------+------------+
| 096111111 | 56      | ttl3  | rrrrr | 1444999600 |
+-----------+---------+-------+-------+------------+
| 096111111 | 57      | ttl4  | ttttt | 1444999540 |
+-----------+---------+-------+-------+------------+

我正在使用这样的请求,而且效果很好:

SELECT
      `users`.`userPhone`,
      `users`.`name`,
      `users`.`address`,
      `users`.`car`,
      (SELECT `title` FROM `orders` WHERE `orders`.`userPhone` = `users`.`userPhone` AND `orders`.`orderTS` < NOW()  ORDER BY `orders`.`createdTS` DESC LIMIT 1 ) as `title`,
      (SELECT `descr` FROM `orders` WHERE `orders`.`userPhone` = `users`.`userPhone` AND `orders`.`orderTS` < NOW()  ORDER BY `orders`.`createdTS` DESC LIMIT 1 ) as `descr`
FROM
              `users`
               LEFT JOIN `orders` USING (`userPhone`)
WHERE 
               `users`.`userPhone` like '%1111%';

但我认为其他SELECT工作缓慢。有没有更好更快的方法来解决它?

如何使用其他请求获得相同的结果(可能没有其他SELECT)。

2 个答案:

答案 0 :(得分:2)

正确的语法JOIN将为您完成所有这些工作,而不需要内部SELECT并且更快。

SELECT
      `users`.`userPhone`,
      `users`.`name`,
      `users`.`address`,
      `users`.`car`,
      `orders`.`title`,
      `orders`.`desc`
FROM `users`
     JOIN `orders` ON `orders`.`phone` = `users`.`phone`
WHERE 
      `users`.`userPhone` like '%1111%'
  AND `orders`.`orderTS` < NOW() 
ORDER BY `orders`.`orderTS` DESC
LIMIT 1;

如果您想要所有这些记录,请删除LIMIT 1

答案 1 :(得分:0)

如果您正在使用内部SELECT

,则无需JOIN或LEFT JOIN任何表格

试试这个

SELECT
      `users`.`userPhone`,
      `users`.`name`,
      `users`.`address`,
      `users`.`car`,
      (SELECT `title` FROM `orders` WHERE `orders`.`userPhone` = `users`.`userPhone` AND `orders`.`orderTS` < NOW()  ORDER BY `orders`.`createdTS` DESC LIMIT 1 ) as `title`,
      (SELECT `descr` FROM `orders` WHERE `orders`.`userPhone` = `users`.`userPhone` AND `orders`.`orderTS` < NOW()  ORDER BY `orders`.`createdTS` DESC LIMIT 1 ) as `descr`
FROM
              `users`
WHERE 
               `users`.`userPhone` like '%1111%';

这应该更快