0

I'm trying to join a different column (part_type_n (where n ranges from 1 to 54)) on Table1 with the same column (id, primary, autoinc) on Table2.

Schema:

Table1
==============
part_type_1
.
.
.
part_type_54



Table2
=============
id

I tried the obvious query (php generated, looping through n from 1 to 54), omitted repetitive stuff in ...:

SELECT * FROM Table1 JOIN Table2 on (Table1.part_type_1=Table2.id), ..., (Table1.part_type_54=Table2.id)

I receive this error:

1066 - Not unique table/alias: 'Table2'

How do I join these two tables?

Community
  • 1
  • 1
ina
  • 18,561
  • 37
  • 117
  • 197
  • In this case, would it be better to just use 54 separate calls instead of a single call? – ina Oct 13 '13 at 01:41
  • Do you really want to select only those records from table1 which have table2 records matching all 54 part_type values? –  Oct 13 '13 at 09:06

3 Answers3

0

You will have to join the table on it self again multiple times.

SELECT * FROM table1 t1 
INNER JOIN table2 t2 on t2.Id=t1.part_type_1 
INNER JOIN table2 t3 on t3.id = t1.part_type_54;

Hope this helps!

Sajuna Fernando
  • 1,314
  • 9
  • 15
0

As an alternative to writing a query with 54 table aliases, you could consider joining to the table once - like so:

select ...
from Table1 t1
join Table2 t2
  on t2.id in (t1.part_type_1, t1.part_type_2, ... t1.part_type_54)
0

It worked for me to get my required result as one row of which matches various categories all stored in one table column.

Query

       SELECT cm3.*, xp.post_title,GROUP_CONCAT(DISTINCT sc.name) AS cate_list
       FROM `xld_posts` xp 
       JOIN course_map cm0 ON cm0.course_id = xp.ID
       JOIN course_map cm1 ON cm1.course_id = cm0.course_id  AND cm0.id = 3
       JOIN course_map cm2 ON cm2.course_id = cm1.course_id  AND cm1.id = 6
       JOIN course_map cm3 ON cm3.course_id = cm2.course_id  AND cm2.id = 11
       JOIN subject_category sc ON cm3.id = sc.id
       GROUP by post_title ORDER BY post_title

Note: the categories values 3, 6, and 7 are got from form sumbit. Thus if your form has more than three or less your query should dynamically created and join each table with previous table.

:) Happy if any one felt useful.

Govindaraj
  • 33
  • 7