SELECT a.tag,CONCAT(u.first_name,' ',u.last_name)
FROM assets a
LEFT JOIN (SELECT asset_id,assigned_to_id
FROM asset_activity
WHERE assigned IN (SELECT MAX(assigned)
FROM asset_activity
GROUP BY asset_id))
v ON v.asset_id = a.id
LEFT JOIN users u ON v.assigned_to_id = u.id
WHERE ($1 IS NULL OR u.last_name LIKE $1)
由于MySQL在子查询上使用左连接执行可怕,我需要找到一些其他方法来执行此操作。我可以在select中选择子查询所需的内容,但它必须是有条件的。它应该只返回与LIKE匹配的记录,并且对于子查询,它仍将从赋值为allocate_to的资产返回一个记录,所以我不能这样做。
执行计划:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY a ALL null null null null 1,447
1 PRIMARY <derived2> ALL null null null null 1,396
1 PRIMARY u eq_ref PRIMARY PRIMARY 4 v.assigned_to_id 1
2 DERIVED asset_activity ALL null null null null 1,400 Using where
3 DEPENDENT SUBQUERY asset_activity index null asset_id 4 null 1,400 Using filesort
的索引:
Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment
assets 0 PRIMARY 1 id A 144 "" BTREE ""
assets 1 serial 1 serial A 1447 YES BTREE ""
assets 1 serial 2 cal_num A 1447 YES BTREE ""
Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment
asset_activity 0 PRIMARY 1 id A 1400 "" BTREE ""
asset_activity 1 asset_id 1 asset_id A "" BTREE ""
asset_activity 1 location_id 1 location_id A YES BTREE ""
asset_activity 1 assigned_to_id 1 assigned_to_id A YES BTREE ""
asset_activity 1 assigned_to_table 1 assigned_to_table A YES BTREE ""
asset_activity 1 created 1 created A "" BTREE ""
答案 0 :(得分:0)
好的,这就是我最终的表现:
SELECT a.tag,CONCAT(u.first_name,' ',u.last_name)
FROM assets a
LEFT JOIN asset_activity v ON v.asset_id = a.id
LEFT JOIN asset_activity v2 ON v2.asset_id = a.id
AND (v.assigned < v2.assigned OR v.assigned = v2.assigned AND v.id < v2.id)
LEFT JOIN users u ON v.assigned_to_id = u.id
WHERE v2.id IS NULL
AND ($1 IS NULL OR u.last_name LIKE $1)
这比具有子查询的子查询上的左连接要好得多。 .0064秒与另一种方法的5秒或更长时间相比,当我将其绑定到我的代码中的网格,分页等时变得更多。