开发者

mysql select from one table if its name is in another table

So what I have is something like this:

main_table

id | in_table | in_tables_id | points
1  | t1       | 1            | 1
2  | t2       | 1            | 4
3  | t2       | 2            | 3
4  | t1       | 2            | 2

and then tables

table1 - which in my main_table is marked as t1

id | content_id
1  | 1
2  | 2

table2 - which in my main_table is marked as t2

id | content_id
1  | 1
2  | 2

content

id | category_id | content
1  | 1           | aaa
2  | 2           | bbb

categories

id | name 
1  | first
2  | seccond
3  | third

So my first table "main_table" has ids of entries from "table1" and "table2" for which users got their points, those entries are connected to "content" by content_id = id from "content" table; and that content in "content" table is allways in some category from "categories" table.

What I want is to sum all points from "main_table" by categories from "categories" table.

The main problem for m开发者_运维技巧e is to somehow "connect" identifiers from "main_table" like t1, t2 with tables "table1", "table2", is there a way to do it?


I recommend restructuring your DB. Have a look at normal forms and transform your tables into normal form, e.g. don't use separate tables, but store the "table name" in a column, so you can do easy joins.

For your current table layout use something like the following join conditions:

select *
from main_table mt
inner join table1 t1
on mt.in_table = 't1'
and mt.in_tables_id = t1.id
inner join table2 t2
on mt.in_table = 't2'
and mt.in_tables_id = t2.id
/* repeat for number of tables */
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜