Search code examples
mysqlsqlselectleft-joinclause

In MySQL, how to use a subquery to a left join statement?


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.


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)