这是我要运行的查询:
SELECT
o.id,
history.name,
history.id AS historyId
FROM
order_sheet AS o
LEFT JOIN(
SELECT
h.detail,
h.eid,
h.date_change
FROM
order_history AS h
WHERE
h.id_order_sheet = o.id
ORDER BY
h.id
DESC
LIMIT 0, 1
) history
ON
history.id_order_sheet = o.id
ORDER BY
o.id
LIMIT 0, 150;
第二个选择中的我的问题。它不知道o.id。
请问您知道如何执行此操作吗?
我将解释我该怎么做:)
我要选择插入到表 order_history 中的最后一个元素,其值为 order_history.id_order_sheet ===到order_sheet.id < / p>
谢谢您的帮助
答案 0 :(得分:0)
您可以在下面尝试
SELECT
o.id,
history.name,
history.id AS historyId
FROM
order_sheet AS o
LEFT JOIN(
SELECT
h.detail,
h.eid,
h.date_change
FROM
order_history AS h join order_sheet o1
on
h.id_order_sheet = o1.id
ORDER BY
h.id
DESC
LIMIT 0, 1
) history
ON
history.id_order_sheet = o.id
ORDER BY
o.id
LIMIT 0, 150;
答案 1 :(得分:0)
我们可能会使用不相关的子查询来重写您的联接:
SELECT
o.id,
h2.name,
h2.id AS historyId
FROM order_sheet AS o
LEFT JOIN
(
SELECT id_order_sheet, MAX(id) AS max_id
FROM order_history
GROUP BY id_order_sheet
) h1
ON o.id = h1.id_order_sheet
INNER JOIN order_history h2
ON h1.id_order_sheet = h2.id_order_sheet AND h1.id = h2.max_id
ORDER BY
o.id
LIMIT 0, 150;
答案 2 :(得分:0)
您要尝试做的是横向联接,而MySQL目前尚不支持。
但是,不难获得每个订单ID的最新历史记录。您不需要加入。
select id_order_sheet, name, id as history_id
from order_history
where id in (select max(id) from order_history group by id_order_sheet)
order by id_order_sheet;
答案 3 :(得分:0)
很明显我无法测试,但这是一种方法:
SELECT
o.id,
h.name,
h.id AS history_id,
h.detail,
h.eid,
h.date_change
FROM order_sheet o
LEFT JOIN order_history h ON h.id_order_sheet = o.id
WHERE h.id IN (
SELECT MAX(id)
FROM order_history
GROUP by id_order_sheet
);