title: Design constraints in SQL tables
body: <p>I'm designing the database and have a problem with how to create a specific constraint.
  Here's an simple version of the problem:</p>
  
  <pre class="lang-sql prettyprint-override"><code>-- pk, fk full descriptions omitted for for brevity
  
  create table labs (
      -- pk
      id uuid
  );
  
  create table tests (
      -- pk
      id uuid,
  
      -- lab_id + code = unique
      lab_id uuid, --FK to labs
      code character varying
  );
  
  create table panels (
      -- pk
      id uuid,
  
      -- lab_id fk to labs
      lab_id uuid
  );
  
  create table panels_tests (
      -- pk
      id uuid,
  
      -- how to ensure panel_id and test_id have reference to entities with the same lab code?
      panel_id uuid,
      test_id uuid
  );
  </code></pre>
  
  <p>So is there a way to make sure panel_id and test_id in the panels_tests table have reference to entities with the same lab code? Or may be it's better to be done through an app business logic?</p>
  
  <p>Thanks.</p>