开发者

What kind of JOIN should I use here?

I'm new to JOINS in MySql.

I have six tables: t1, t2, t3, t4, t5, t6. And I also have one main table: main_table. TOTAL 7 TABLES!

The first column of ALL tables is called classified_id.

If the user searches for "cars" then the main table will match everything in table t1 (which is the cars table) where classified_id is the same in both tables.

So:

   SELECT * FROM main_table, t1 WHERE main_table.classified_id=t1.classified_id

This works fine, although I am not sure this is the way to join here. Performance is an issue in my case!

However, here is my problem. Whenever ALL CLASSIFIEDS are searched, then I need to match the main_table.classified_id to the other tables classified_id column and get every classified there is.

How should this query be made up?

    SELECT * FROM main_table, t1, t2, t3, t4, t5, t6 // I have this so far which is not much!

If you need more input just ask and I will update this Q.

Thanks

EDIT: Table setup:

     main_table:              t1:
     ID(PK)                   ID (PK)
     classified_id -> 25      classified_id     ->   25
     category  -> CARS        year     ->    19开发者_Python百科97


If the row would exist in all tables (i.e. every table has a row for a specific classified_id), then you would use an inner join:

SELECT 
   m.classified_id
   ,m.category
   ,t1.year
   ,........
FROM 
   main_table m
   INNER JOIN t1 ON m.classified_id = t1.classified_id
   INNER JOIN t2 ON m.classified_id = t2.classified_id
   INNER JOIN t3 ON m.classified_id = t3.classified_id
   INNER JOIN t4 ON m.classified_id = t4.classified_id
   INNER JOIN t5 ON m.classified_id = t5.classified_id
   INNER JOIN t6 ON m.classified_id = t6.classified_id

If the row does not exist in every table, then you'd use LEFT JOINS so that rows are not dropped


Use:

   SELECT mt.*,
          t1.*,
          t2.*,
          t3.*,
          t4.*,
          t5.*,
          t6.*
     FROM MAIN_TABLE mt
LEFT JOIN TABLE_1 t1 ON t1.classified_id = mt.classified_id
LEFT JOIN TABLE_2 t2 ON t2.classified_id = mt.classified_id
LEFT JOIN TABLE_3 t3 ON t3.classified_id = mt.classified_id
LEFT JOIN TABLE_4 t4 ON t4.classified_id = mt.classified_id
LEFT JOIN TABLE_5 t5 ON t5.classified_id = mt.classified_id
LEFT JOIN TABLE_6 t6 ON t6.classified_id = mt.classified_id

I used LEFT JOINs because if JOIN was used - records would be omitted that did not have a supporting record in at least one of the t1/2/3/4/5/6 tables. You might find this link helpful for understanding JOINs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜