gpt4 book ai didi

mysql - 左连接两个表,其中我的变量小于 5

转载 作者:行者123 更新时间:2023-11-29 11:05:44 24 4
gpt4 key购买 nike

我正在创建一个查询,选择两个表并通过计算一个表中的字段来创建一个总变量。示例:

 Table A:

ID | email
1 | test@test
2 | test2@test
3 | test3@test

表B

ID | email_id  | username_id
1 | 1 | 11
2 | 1 | 22
3 | 2 | 33

我的查询:

select a.id, a.email, count(c.id) as total
from tableA a
left join tableC c on c.email_id = a.id AND total <= 5
group by a.email LIMIT 1

输出:

 Unknown column 'total' in 'on clause

我需要选择第一个总数 <= 5 的“a.id”。我该怎么做?

最佳答案

逻辑上,SelectWhere 子句之后处理,因此您不能在同一 Where 子句中使用别名。

使用HAVING子句

select a.id, a.email, count(c.id) as total
from tableA a
left join tableC c on c.email_id = a.id
group by a.email
Having count(c.id) <= 5
LIMIT 1

我认为Mysql也允许你这样做

Having total <= 5

关于mysql - 左连接两个表,其中我的变量小于 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41446963/

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