gpt4 book ai didi

php - 使用 CTE 的 SQL 错误

转载 作者:行者123 更新时间:2023-11-29 03:59:57 25 4
gpt4 key购买 nike

我收到这个错误:

查询错误:您的 SQL 语法有误;查看与您的 MariaDB 服务器版本对应的手册,了解在“;WITH convs AS ( select c.id, c.title, c.seen, c.id_receiver, c.id_send' at line 1

当我使用这个查询时:

$query = ";WITH convs AS (
select c.id, c.title, c.seen, c.id_receiver, c.id_sender
from conversations c
)
select id, title, seen, id_receiver, id_sender
from convs
where id_receiver = '5'
order by title desc limit 0,25";

$res = mysqli_query($connection ,$query);

我错过了什么吗?非常感谢您的帮助。

PS:我最小化了查询以使其在此上下文中变得简单,如果您帮助我找到解决方案,我可能会遇到完整查询的另一个问题。所以我可能会回来找你寻求更多帮助。提前致谢。

编辑(整个查询)

$query = "WITH convs AS (
select c.id, c.title, c.seen, c.id_receiver, c.id_sender,
(select max(date) from messages where id_conversation = c.id and id_user <> '$iduser') as last_msg,
(select top 1 id_user from messages where id_conversation = c.id and id_user <> '$iduser' order by date desc) as last_user,
(select count(distinct id_user) from messages where id_conversation = c.id) as nbruser,
(select count(*) from messages where id_conversation = c.id) as nbrmsg,
(select username from users where id = c.id_sender) as sender, (select username from users where id = c.id_receiver) as receiver,
(select count(*) from deleted_conversations where id_user='$iduser' and id_conversation=c.id) as deleted,
from conversations c
)
select id, title, seen, id_receiver, id_sender, receiver, sender, last_msg, last_user, deleted, nbruser, nbrmsg
from convs
where (id_receiver = '$iduser' or (id_sender == '$iduser' and nbruser > 1)) and deleted = 0
order by last_msg desc limit $pageLimit,$REC_PER_PAGE";

促使我使用 CTE 的原因是需要在 where 子句中使用别名。如您所见,我有很多。

能否举例说明如何使用 View /临时表来实现我的目的?

最佳答案

MySQL/MariaDB 不支持 CTE。另外,在这种情况下完全没有必要:

    select id, title, seen, id_receiver, id_sender
from conversations c
where id_receiver = '5'
order by ?? desc
limit 0, 25;

注意:您还需要为 order by 指定列。

对于更复杂的示例,您可以使用子查询、 View 和/或临时表。

关于php - 使用 CTE 的 SQL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36969171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com