此 SELECT 按预期返回结果。
SELECT
h.id,
h.rec_inv_num,
h.rec_inv,
h.trans_date,
h.trans_branch,
h.trans_type,
h.trans_number
FROM
1_trans_history h
WHERE
h.id IN (SELECT
h.id
FROM
1_trans_history_entries_stat s
LEFT JOIN
1_trans_history_entries e ON e.id = s.fk_trans_history_entries_id
LEFT JOIN
1_trans_history h ON h.id = e.fk_trans_history_id
LEFT JOIN
addresses a ON a.id = h.i_fk_addresses_id
WHERE
s.item_stat = 2
GROUP BY h.id
ORDER BY a.company , h.i_surname , h.i_middle_init , h.i_first_name , h.i_title);
我现在需要锁定表以进行写入,因此我添加了此内容,但收到“错误代码:1100 表 '1_trans_history' 未使用 LOCK TABLES 锁定”
LOCK TABLES
1_trans_history h WRITE,
1_trans_history_entries e WRITE,
1_trans_history_entries_stat s WRITE;
我理解“您不能在单个查询中多次使用锁定的表。请改用别名,在这种情况下,您必须分别为每个别名获取锁定:”
所以我已将代码更改为此,但我收到相同的错误
LOCK TABLES
1_trans_history h WRITE,
1_trans_history_entries e WRITE,
1_trans_history_entries_stat s WRITE,
1_trans_history h2 WRITE,
1_trans_history_entries e2 WRITE,
1_trans_history_entries_stat s2 WRITE,
addresses a2 WRITE;
SELECT
h.id,
h.rec_inv_num,
h.rec_inv,
h.trans_date,
h.trans_branch,
h.trans_type,
h.trans_number
FROM
1_trans_history h
WHERE
h.id IN (SELECT
h2.id
FROM
1_trans_history_entries_stat s2
LEFT JOIN
1_trans_history_entries e2 ON e2.id = s2.fk_trans_history_entries_id
LEFT JOIN
1_trans_history h2 ON h2.id = e2.fk_trans_history_id
LEFT JOIN
addresses a2 ON a2.id = h2.i_fk_addresses_id
WHERE
s2.item_stat = 2
GROUP BY h2.id
ORDER BY a2.company , h2.i_surname , h2.i_middle_init , h2.i_first_name , h2.i_title);
unlock tables;
最佳答案
我认为 LOCK 语句中的别名存在一些混淆。我已删除 1_trans_history 表的别名之一并将其显式添加到 LOCK 语句中。为了更加清晰起见,我还重命名了 a2 和 s2 别名。
LOCK TABLES
1_trans_history WRITE,
1_trans_history h WRITE,
1_trans_history_entries e WRITE,
1_trans_history_entries_stat s WRITE,
addresses a WRITE;
SELECT
id,
rec_inv_num,
rec_inv,
trans_date,
trans_branch,
trans_type,
trans_number
FROM
1_trans_history
WHERE
1_trans_history.id IN (SELECT
h.id
FROM
1_trans_history_entries_stat s
LEFT JOIN
1_trans_history_entries e ON e.id = s.fk_trans_history_entries_id
LEFT JOIN
1_trans_history h ON h.id = e.fk_trans_history_id
LEFT JOIN
addresses a ON a.id = h.i_fk_addresses_id
WHERE
s.item_stat = 2
GROUP BY h.id
ORDER BY a.company , h.i_surname , h.i_middle_init , h.i_first_name , h.i_title);
UNLOCK TABLES;
尝试一下,它应该对你有用。
说实话,我相信唯一需要别名的表是 1_trans_history,但是我知道使用指定的其他别名查询更具可读性。
关于mysql - 表锁定错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22354678/