0

So here's the problem I'm having. I have two separate tables TableA and TableB, TableA has four columns and TableB has two. TableA holds only ids while TableB holds id and string. So I need strings from TableB but based on the ids from TableA

For example:

TableA:

+------+------+-------+------+
| m_id | appi | mainy | desy |
+------+------+-------+------+
| 1    | 6    | 9     | 13   |
+------+------+-------+------+
| 2    | 7    | 10    | 14   |
+------+------+-------+------+
| 3    | 8    | 12    | 15   |
+------+------+-------+------+

TableB

+------+-------+
| t_id | str   |
+------+-------+
| 6    | dude  |
+------+-------+
| 10   | bro   |
+------+-------+
| 9    | lol   |
+------+-------+
| 14   | homie |
+------+-------+

Based on the tables above I need to find out the actual strings based on the ids from TableB, something like SELECT str FROM TableB WHERE t_id = (Ids from TableA WHERE m_id=1). So my expected data should be 'dude' and 'lol' because m_id=1 has two ids 6 and 9, and those ids in TableB have strings 'dude' and 'lol'. I would really appreciate any help and sorry if there's any confusion, please let me know and I'll try to address that.

1
  • 2
    This database design is pretty broken, frankly. You should start by normalizing your data so that you don't have one table (TableB) with data that corresponds unpredictably to 3 different columns in another table (TableA). Commented Dec 10, 2018 at 3:42

2 Answers 2

3

You can do this with a simple JOIN of TableB to TableA, where t_id from TableB must be one of the values of appi, mainy or desy from TableA for a given m_id:

SELECT b.str
FROM TableB b
JOIN TableA a ON b.t_id IN (a.appi, a.mainy, a.desy)
WHERE a.m_id = 1

Output:

str
dude
lol

Demo on dbfiddle

Sign up to request clarification or add additional context in comments.

4 Comments

On large tables this would become slower than the "exists" function.
@cornel.raiu on large tables the EXISTS function will become very slow because the WHERE condition has to be computed for every row in the table.
you are right. Just did a quick benchmark on this case. It turns out that, when using subqueries, Join is much faster than EXISTS. +1 for you :)
Dude Nick! You're awesome! this totally worked fine for me. Thanks!!
1

You can use exists for the this type of logic:

select b.str
from tableb b
where exists (select 1
              from tablea a
              where a.m_id = 1 and
                    b.t_id in (a.appi, a.mainy, a.desy)
             );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.