From: | Mark Wallace <mwallace(at)dataxdesign(dot)com> |
---|---|
To: | Submit Postgresql Novice <pgsql-novice(at)postgresql(dot)org> |
Cc: | "Bee(dot)Lists" <bee(dot)lists(at)gmail(dot)com> |
Subject: | Re: Outer Right Join? |
Date: | 2020-02-20 16:06:22 |
Message-ID: | 97CC8DF1-ED65-4C25-B7C8-0B4F676330E5@dataxdesign.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-novice |
First problem is the database design is no good.
1. If companies <—> products is many-to-many, you need a cross-reference table between them.
2. If companies <—> contracts is one-to-one, optional, then contracts should be a list of contracts (not of companies), or, if there are no significant attributes of a contract, merged into companies as a status flag or boolean (is there a contract with this company or not?).
It is almost never a good idea to have the same entity (in this case, companies) stored in more than one table solely because of varying attribute or relationship values.
It’s not a good idea to try to twist SQL into compensating for a confused database design.
Note: There is no way that SELECT DISTINCT needs to be part of your solution.
You might want to have a look at a book such as this one:
https://www.amazon.com/Data-Analysis-Database-Design-David/dp/0750650869 <https://www.amazon.com/Data-Analysis-Database-Design-David/dp/0750650869>
Cheers,
Mark
> On Feb 20, 2020, at 03:04, Bee.Lists <bee(dot)lists(at)gmail(dot)com> wrote:
>
> I’m looking for a three-table join. The SQL that I have isn’t working.
>
> companies table - list of companies
> products table - list of products sold by those companies
> contracts table - list of companies that hold ad contracts
>
> I need to ask:
>
> "Show me the queried product (i.e.: Screwdriver) listings with their company names that DO NOT have contracts"
>
> SELECT DISTINCT ON ("listings"."product")
> "listings"."product", "companies"."name"
> FROM "listings"
> RIGHT OUTER JOIN "contracts" ON ("contracts"."companyid" = "listings"."companyid")
> LEFT JOIN "companies" ON ("companies"."scid" = "listings"."companyid")
> WHERE (("listings"."product" ILIKE '%screwdriver%' ESCAPE '\'))
>
> The result works without the RIGHT OUTER JOIN in there. When the RIGHT OUTER JOIN is in there, I get a hitlist of zero. Currently I have no contracts in that table, so those two queries should be the same. They are not.
>
> To repeat, I want any company’s products that are in the contracts table, to not show up. “products with no contract”.
>
> Any inside as to how I can get this to work, appreciated.
>
>
> Cheers, Bee
>
>
>
>
>
>
From | Date | Subject | |
---|---|---|---|
Next Message | David G. Johnston | 2020-02-20 16:28:00 | Re: Outer Right Join? |
Previous Message | Bee.Lists | 2020-02-20 08:04:59 | Outer Right Join? |