mysql 计数问题

发布于 2024-11-16 06:56:44 字数 499 浏览 2 评论 0原文

SELECT count( t1.id ) , t2.special_value
FROM table_1 AS t1, table_2 AS t2
WHERE t1.`group` = 'val'
AND t2.code = 'val'

返回

count - normal value
special_value - NULL

SELECT t2.special_value
FROM table_2 AS t2
WHERE t2.code = 'val'

返回

special_value - another normal value

为什么第一个查询工作错误?..

目前,我需要

(count( t1.id ) + t2.special_value)
SELECT count( t1.id ) , t2.special_value
FROM table_1 AS t1, table_2 AS t2
WHERE t1.`group` = 'val'
AND t2.code = 'val'

returns

count - normal value
special_value - NULL

but

SELECT t2.special_value
FROM table_2 AS t2
WHERE t2.code = 'val'

returns

special_value - another normal value

why first query works wrong?..

currently, i need

(count( t1.id ) + t2.special_value)

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

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

发布评论

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

评论(1

水水月牙 2024-11-23 06:56:44

这就是为什么您永远不应该使用 SQL'89 隐式连接语法。

您没有导致交叉连接的连接条件。

使用显式连接语法重写查询:

SELECT count( t1.id ) , t2.special_value
FROM table_1 AS t1
INNER JOIN table_2 AS t2 ON (t1.`group` = t2.code)    <<-- join condition here
WHERE ....                                            <<-- filter condition here
GROUP BY ....                                         <<-- group by field here

我不知道表 t1 和 t2 是如何链接的,因此您必须稍微调整一下,但这就是它应该如何工作。
并且请永远不要再次使用隐式 where 连接。

备注
我想知道 p.`group`pp.code 是什么,但我猜你想写 t1.`group` > 和 t2.code

如果字段和表名是保留字,则只需在 ` 反引号中转义它们即可。
就我个人而言,所有这些反引号让我头晕,但这只是我。

This is why you should never use SQL'89 implicit join syntax.

You have no join condition resulting in a cross join.

Rewrite the query using explicit join syntax:

SELECT count( t1.id ) , t2.special_value
FROM table_1 AS t1
INNER JOIN table_2 AS t2 ON (t1.`group` = t2.code)    <<-- join condition here
WHERE ....                                            <<-- filter condition here
GROUP BY ....                                         <<-- group by field here

I don't know how table t1 and t2 are linked, so you'll have to tweak this a bit, but that's how it supposed to work.
And please never ever use implicit where joins again.

Remarks
I'm wondering what p.`group` and pp.code are, but I'm guessing you meant to write t1.`group` and t2.code

You only need to escape fields and tablenames in ` backticks if they are reserved words.
Personally all those backticks make me dizzy, but that's just me.

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