我有一个在命令行上运行的sql查询(在我的情况下,使用GUI运行查询),但是在PHP上,通过mysqli_query()函数,它不起作用。该错误是重复的键错误。
奇怪的是:错误不存在。它在命令行上运行的事实证明了这一点。此外,在进一步调查后,记录显示唯一密钥从未被破坏。不过,mysqli_query()会抛出唯一的键错误。
我的查询是:
UPDATE
frequencia
INNER JOIN
(
SELECT
*,
@row_number_aux : =
CASE
WHEN
@atual_aux = disciplina_id
THEN
@row_number_aux + 1
ELSE
1
END
AS "row_number", @atual_aux : = disciplina_id AS "disciplina_atual"
FROM
frequencia
WHERE
frequencia.data > "2019-06-17"
AND frequencia.aluno_id IN
(
8835, 5553, 3488, 7769, 143, 4406, 1472, 698, 8731, 5221, 4240, 4934, 8426, 8107, 5180, 2146, 5589, 4565
)
)
frequencia_aux
ON frequencia.id = frequencia_aux.id
INNER JOIN
(
SELECT
*,
@row_number : =
CASE
WHEN
@atual = disciplina_id
THEN
@row_number + 1
ELSE
1
END
AS "row_number", @atual : = disciplina_id AS "disciplina_atual"
FROM
(
SELECT
disciplina_id,
data,
tempo,
turma_id
FROM
frequencia
WHERE
data > "2019-06-17"
AND turma_id = "87"
GROUP BY
data,
disciplina_id,
tempo
)
frequencia
)
aux
ON frequencia_aux.disciplina_id = aux.disciplina_id
AND frequencia_aux.data = aux.data
AND frequencia_aux.row_number = aux.row_number
SET
frequencia.turma_id = aux.turma_id,
frequencia.tempo = aux.tempo;
我以前已经使用@变量,没有问题,并且使用过所有类型的复杂语句,但从未遇到过这样的错误。有人曾经经历过类似的事情吗?
答案 0 :(得分:0)
已解决。
问题是:在mysql cli上直接运行时@变量似乎是自动初始化的,而不是通过mysqli_query进行的。 一个简单的子查询联接就完成了工作。
感谢@ spencer7593的见识。
最终的sql:
UPDATE
frequencia
INNER JOIN
(
SELECT
*,
@row_number_aux :=
CASE
WHEN
@atual_aux = disciplina_id
THEN
@row_number_aux + 1
ELSE
1
END
AS "row_number", @atual_aux := disciplina_id AS "disciplina_atual"
FROM
frequencia
join (select @row_number_aux := 0, @atual_aux := 0) xxx
WHERE
frequencia.data > "2019-06-17"
AND frequencia.aluno_id IN
(
8835, 5553, 3488, 7769, 143, 4406, 1472, 698, 8731, 5221, 4240, 4934, 8426, 8107, 5180, 2146, 5589, 4565
)
)
frequencia_aux
ON frequencia.id = frequencia_aux.id
INNER JOIN
(
SELECT
*,
@row_number :=
CASE
WHEN
@atual = disciplina_id
THEN
@row_number + 1
ELSE
1
END
AS "row_number", @atual := disciplina_id AS "disciplina_atual"
FROM
(
SELECT
disciplina_id,
data,
tempo,
turma_id
FROM
frequencia
WHERE
data > "2019-06-17"
AND turma_id = "87"
GROUP BY
data,
disciplina_id,
tempo
)
frequencia
join (select @row_number := 0, @atual := 0) xxx
)
aux
ON frequencia_aux.disciplina_id = aux.disciplina_id
AND frequencia_aux.data = aux.data
AND frequencia_aux.row_number = aux.row_number
SET
frequencia.turma_id = aux.turma_id,
frequencia.tempo = aux.tempo