已阅读所有类似的qs,但无法应用于我的sql
想要选择所有客户并插入最后一个操作记录。 下面的sql首先选择max actionid,然后在另一个子查询中使用它 - 这需要5 +秒才能运行;(
请告知TQ
SELECT cus.cusid,cus.FirstName,cus.Surname,
lastact.actionid, lastact.actiondate, lastact.siteid
FROM cus
LEFT JOIN(
SELECT MAX(actionid) AS maxactionid, cusid
FROM `action`
INNER JOIN `event` ON event.eventid = action.`eventid`
GROUP BY cusid
) AS maxactionid ON maxactionid.cusid = cus.cusid
LEFT JOIN (
SELECT
action.actionid,
action.actiondate,
event.cusid,
event.siteid
FROM
`action`
INNER JOIN `event`
ON event.eventid = action.eventid
ORDER BY actionid DESC
) AS lastact ON lastact.actionid = maxactionid
WHERE UCASE(CONCAT(firstname, surname)) LIKE '%JIM%HEMM%'
想法的TQ - 请参阅以下内容:
1)限制的想法,为lastact.actionid,lastact.actiondate,lastact.siteid提供了null结果 - 但确实在0.075秒内运行! 遗憾的是,这个想法失败了
SELECT cus.cusid,cus.FirstName,cus.Surname, lastact.actionid, lastact.actiondate, lastact.siteid
FROM cus
LEFT JOIN (SELECT action.actionid, action.actiondate, event.cusid, event.siteid
FROM action
INNER JOIN event ON event.eventid = action.eventid
ORDER BY actionid DESC LIMIT 1
) AS lastact ON lastact.cusid = cus.cusid
WHERE UCASE(CONCAT(firstname, surname)) LIKE '%JIM%HEMM%'
2)原始查询的EXPLAIN结果为:
3)添加LIKE' JIM%'和cus.surname LIKE' HEMM%'不会对查询时间产生太大影响,但会根据建议
包含嗨 - 通过使用每个人的想法获得了很好的结果 - 谢谢
1)改变了哪里有cus.FirstName LIKE' JIM%'和cus.surname LIKE' H%'
2)在姓氏,姓氏
上添加了索引3)在行动表中添加了cusid(不再需要事件表)
4)在动作子查询
之外移动查找表(不是原始问题)完成的sql看起来像(在0.063秒内运行 - 用只有一个字母的姓氏测试!)
SELECT cus.cusid,cus.FirstName,cus.Surname, lastact.actionid, lastact.actiondate, lastact.siteid, actiontype.action,
FROM cus
LEFT JOIN (
SELECT action.actionid, action.actiondate, event.cusid, event.siteid
FROM action
ORDER BY actionid DESC
) AS lastact ON lastact.cusid = cus.cusid
LEFT JOIN actiontype ON actiontype.actiontypeid = lastact.typeid
WHERE cus.FirstName LIKE 'JIM%' AND cus.surname LIKE 'H%'
GROUP BY lastact.cusid
答案 0 :(得分:0)
总而言之,我制作的sql(显然没有经过测试,你可能需要修复一些东西):
SELECT cus.cusid,cus.FirstName,cus.Surname,
maxaction.actionid, maxaction.actiondate, maxaction.siteid
FROM cus
LEFT JOIN(
SELECT actionid AS maxaction, action.actiondate, event.cusid, event.siteid
FROM `action`
INNER JOIN `event` ON event.eventid = action.eventid
order by actionid desc limit 1
) AS maxaction ON maxaction.cusid = cus.cusid
WHERE cus.FirstName like 'JIM%' and cus.surname like 'HEMM%'