我有 2 个通过 userPhone
链接的表格。
表格用户
+-----------+-------+----------+--------+
| 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)。
最佳答案
语法正确的 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
关于php - MySQL。从第二个表中选择最后一条记录(按创建时间),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33348713/