"invalid reference to FROM-clause entry for table" in Postgres query
<p>I have the following query:</p>

<pre><code>query =
    "SELECT
      data #&gt;&gt; '{id}'          AS id,
      data #&gt;&gt; '{name}'        AS name,
      data #&gt;&gt; '{curator}'     AS curator,
      data #&gt;  '{$isValid}'    AS \"$isValid\",
      data #&gt;  '{customer}'    AS customer,
      data #&gt;  '{$createdTS}'  AS \"$createdTS\",
      data #&gt;  '{$updatedTS}'  AS \"$updatedTS\",
      data #&gt;  '{$isComplete}' AS \"$isComplete\",
      (count(keys))::numeric as \"numProducts\",
      created_at
    FROM
      appointment_intakes,
      LATERAL jsonb_object_keys(data #&gt; '{products}') keys
    INNER JOIN
      appointment_intake_users
    ON
      appointment_intake_users.appointment_intake_id = appointment_intakes.id
    #{where_clause}
    GROUP BY id"
</code></pre>

<p>And it is causing the following error:</p>

<blockquote>
  <p>invalid reference to FROM-clause entry for table "appointment_intakes"</p>
</blockquote>

<p>The error started happening after I added:</p>

<pre><code>LATERAL jsonb_object_keys(data #&gt; '{products}') keys
</code></pre>

<p>and</p>

<pre><code>(count(keys))::numeric as \"numProducts\"
</code></pre>

<p>because I needed to calculate the number of products.</p>

<p>How can I avoid this error from happening?</p>