I'm sure this question has been asked a lot (in many ways) but need help with extracting data from two tables matching certain data. It is probably a simple answer but I'm just starting on SQL.
I have two tables:
parts table (p)
code | code_desc | part_no | part |
---|---|---|---|
23 | Fruits | 001 | Banana |
23 | Fruits | 002 | Apple |
24 | Veggies | 010 | Celery |
24 | Veggies | 010 | Onion |
25 | Misc | 125 | Sanitizer |
codes table (c)
code | contract |
---|---|
23 | Albany |
24 | Detroit |
25 | Chicago |
I simply want to display the code description, matching codes on each table. e.g.,
CD | contract | descrip |
---|---|---|
23 | Albany | Fruits |
23 | Albany | Fruits |
24 | Detroit | Veggies |
24 | Detroit | Veggies |
25 | Chicago | Sanitizer |
I have been tinkering with joins, left and right (literally), but seem to be getting ALL the rows returned from the first table.
CD | contract | descrip |
---|---|---|
23 | Albany | Fruits |
24 | Detroit | Veggies |
25 | Chicago | Sanitizer |
this is one of the code examples I have, using inner join. I've tried left/right outer join as well, same results.
SELECT p.code, p.contract, c.code_desc
FROM db1.parts p INNER JOIN db1.codes c ON p.code = c.code
also
SELECT p.code, p.contract, c.code_desc
FROM db1.parts, db1.codes c where p.code = c.code
Thanks in advance and my apologies if this is so trivial ;)
CodePudding user response:
I think since you state the query you have is returning all rows from the first table (why wouldn't it?) you just need to add distinct
to your existing query - although the column aliases you've used do not align with the tables in your question.
SELECT DISTINCT p.code, c.contract, p.code_desc
FROM db1.parts p
INNER JOIN db1.codes c ON p.code = c.code