SQL: finding one field in one table for multiple values ​​in another table?

(Not sure if the name of this question really makes sense, but what I want to do is pretty simple)

The table data looks something like this:

Table Foo
---------------------------------
| bar1_id | bar2_id | other_val |
---------------------------------

Table Bar
--------------------
| bar_id | bar_desc|
--------------------

How do I create a selection that returns a table that looks like this:

---------------------------------------------------------
| bar1_id | bar1_desc | bar2_id | bar2_desc | other_val |
---------------------------------------------------------

i.e. I want to grab every row from Foo and add to the column containing the description of this bar_id from Bar. Thus, there may be some lines from Bar that do not fall into the result set, but each line of Foo should be in it.

Also, this is postgres, if that matters.

+3
source share
4 answers
SELECT F.bar_id1, 
    (SELECT bar_desc FROM Bar B WHERE (F.bar_id1 = B.bar_id)),
    F.bar_id2, 
    (SELECT bar_desc FROM Bar B WHERE (F.bar_id2 = B.bar_id)),
    F.other_val
FROM FOO F;
+2
source

( , ), ...

. , foo 3 ? ? ( , . " " , ).

- " " ( , foo, foo-to-bar, . " " ). foo, ( SQL). - , CrossTab.

+2
SELECT
  foo.bar1_id, bar1.bar_desc AS bar1_desc,
  foo.bar2_id, bar2.bar_desc AS bar2_desc,
  foo.other_val
FROM
  foo
  INNER JOIN bar bar1 ON bar1.id = foo.bar1_id
  INNER JOIN bar bar2 ON bar2.id = foo.bar2_id

, bar1_id, bar2_id foo. null, INNER JOIN LEFT OUTER JOIN.

+1
select f.bar1, b1.desc, f.bar2, b2.desc, f.value 
from foo as f, bar as b1, bar as b2 
where f.bar1 = b1.id 
  and f.bar2 = b2.id
0

Source: https://habr.com/ru/post/1723596/


All Articles