两个简单的 MySQL 语句导致语法错误

发布于 2024-10-01 06:08:43 字数 305 浏览 4 评论 0原文

我很困惑。以下 MySQL 查询:

SET @a := 0;   

SELECT * 
  FROM users;

给出错误:

无效查询:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在第 2 行“SELECT * FROM users”附近使用的正确语法`

当我切换语句的顺序时,我再次在第 2 行遇到相同的错误(即使我切换它们)

但是,任何一条线本身都运行良好。什么可能导致这种情况?

I'm confounded. The following MySQL query:

SET @a := 0;   

SELECT * 
  FROM users;

Gives the error:

Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT * FROM users' at line 2`

When I switch the order of the statements, I get the same error, again on line 2 (even though I switched them)

However, either line by themselves runs fine. What could possibly cause this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

゛时过境迁 2024-10-08 06:08:43

我打赌您正在尝试在 mysql_query() 中执行此查询(或任何编程语言中的一些类似函数),但它只接受单个查询。所以解决方案是将这个查询分成 2 个调用。

I bet you're trying to perform this query in the mysql_query() (or some similar function from any programming language), but it accepts only single query. So the solution is to split this queries into 2 calls.

傲影 2024-10-08 06:08:43

您可以在一个查询中完成此操作,如下所示:

技巧

select @a:=@a+1, u.* 
from 
 users u 
join (select @a:=0) a

,或者大胆地使用存储过程,这样它始终是一个调用:P

存储过程

drop procedure if exists list_users;
delimiter #

create procedure list_users()
begin
 set @a = 0;
 select @a:=@a+1, u.* from users u;
end #

delimiter ;

call list_users();

PHP 脚本< /强>

$conn = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306);

$result = $conn->query("call list_users()");

while($row = $result->fetch_assoc()){
 ...
}

$result->close();
$conn->close();

you can do it in one query as follows:

The trick

select @a:=@a+1, u.* 
from 
 users u 
join (select @a:=0) a

or be adventerous and use a stored procedure so it's always a single call :P

Stored procedure

drop procedure if exists list_users;
delimiter #

create procedure list_users()
begin
 set @a = 0;
 select @a:=@a+1, u.* from users u;
end #

delimiter ;

call list_users();

PHP script

$conn = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306);

$result = $conn->query("call list_users()");

while($row = $result->fetch_assoc()){
 ...
}

$result->close();
$conn->close();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文