1

Have a problem find a query for my tables

I have 2 tables tab table1 and table2 as follow

table1
id (int) auto_increment
table2_id1(int)
table2_id2(int)
table2_id3(int)
table2_id4(int)

table2

id(int) auto
name (varchar)

that I will do is to get a query to show the name for table2.name insted of the table2_id1 integer.

exampel what I will do and havent a query for

1....test...test...test...test
2....mos...test...mos...mos

my tables as follow

Table1

1   1   1   1   1   
2   2   1   2   2

table2

1   test
2  mos

hope that you can understand what I trying to do, probably some easy way to get the result but I cant find it. Im glad of all help I can get.

2 Answers 2

2

You need to join to table2 with an alias, 4 different times, please note that as Mike points out, this is not a very good structure, and you are better off creating a different table to handle this one-to-many relation, instead of adding columns on table 1

 SELECT Table1.id, a.name AS name1, b.name AS name2, c.name as name3, d.name AS name4
 FROM Table1
      JOIN Table2 a on Table1.table2_id1 = a.id 
      JOIN Table2 b on Table1.table2_id2 = b.id 
      JOIN Table2 c on Table1.table2_id3 = c.id 
      JOIN Table2 d on Table1.table2_id4 = d.id 
Sign up to request clarification or add additional context in comments.

3 Comments

Please explain to the OP what this does and why it is necessary.
This should work. I would note however that this seems like a bit of on odd schema and might be better suited for normalization, so as to prevent having to join to Table2 repeatedly.
Thanks for the help with the query, works perfectly =)) And I have learned a new thing of sql =)). Have a nice weekend
0

Try this

SELECT id, A.name, B.name 
FROM table1 
  LEFT JOIN table2 AS A ON A.id = table1.table2_id1 
  LEFT JOIN table2 AS B ON B.id = table1.table2_id2;

I just included the first two, but you'll be able to add the rest the same way

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.