Question

I tried to count how many new tuples are in a subset of t2 as compared to t1 by

SELECT
  COUNT(t2.id)
FROM (
  (SELECT id, col1 FROM t2 WHERE col2=0 AND col3=0) AS t
  LEFT OUTER JOIN
    t1
  ON
    t.id=t1.id
)
WHERE
  t1.id IS NULL;

The subset is defined by

(SELECT id, col1 FROM t2 WHERE col2=0 AND col3=0) AS t

But the above program doesn't seem to work, issuing errors.

Was it helpful?

Solution

There is no need to enclose the FROM clause in (). You are referencing t2.id in your aggregate COUNT(), but your SELECT list will only produce t.id from the subquery that encapsulates t2. This version addresses the source of your errors:

SELECT
  COUNT(t.id) AS idcount
FROM 
  (SELECT id, col1 FROM t2 WHERE col2=0 AND col3=0) AS t
  LEFT OUTER JOIN t1 ON t.id = t1.id
WHERE t1.id IS NULL

However:

Since your subquery is actually pretty simple, I believe it isn't necessary at all. The whole thing can be done with a LEFT JOIN:

SELECT
  /* The equivalent of COUNT(*) in this context */
  COUNT(t2.id) AS idcount
FROM
  t2 
  LEFT OUTER JOIN t1 ON t2.id = t1.id
WHERE
  t1.id IS NULL
  AND (t2.col2 = 0 AND t2.col3 = 0)

OTHER TIPS

are you sure you don't want to do COUNT(t.id)? t2 is in a subquery and is not available to the main query only t and t1 are available.

The problem is the alias. You have:

select count(t2.id)

But, t2 is defined in the subquery, so it is out of scope.

You want:

select count(t.id)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top