1

我正在尝试做这样的事情:

SELECT COUNT(topic.topic_id) + COUNT(post.post_id)
FROM topic, post WHERE author_id = ?

两个表都有列author_id

我得到column reference "author_id" is ambiguous错误。

我怎么知道它author_id在两个表中都存在?

4

1 回答 1

4

虽然可以,但您很可能不想加入这两个表,因为这可能会导致不同的计数。此相关答案中的解释:
两个 SQL LEFT JOINS 产生不正确的结果

两个子查询最快:

SELECT (SELECT COUNT(topic_id) FROM topic WHERE author_id = ?)
     + (SELECT COUNT(post_id)  FROM post  WHERE author_id = ?) AS result

如果topic_id和在各自的表post_id中定义,您可以稍微简化:NOT NULL

SELECT (SELECT COUNT(*) FROM topic WHERE author_id = ?)
     + (SELECT COUNT(*) FROM post  WHERE author_id = ?) AS result

如果author_id两列中至少有一个是唯一的,那么在这种情况下 aJOIN也可以工作(但速度较慢,我不会使用它):

SELECT COUNT(t.topic_id) + COUNT(p.post_id) AS result
FROM   topic t
LEFT   post  p USING (author_id)
WHERE  t.author_id = ?;

如果您只想输入一次值,请使用CTE

WITH x AS (SELECT ? AS author_id)  -- enter value here
SELECT (SELECT COUNT(*) FROM topic JOIN x USING (author_id))
     + (SELECT COUNT(*) FROM post  JOIN x USING (author_id)) AS result

但一定要了解连接是如何工作的。阅读手册中关于连接的章节。

于 2013-11-03T14:00:37.227 回答