0

I have an interesting situation about my MySQL db structure.

Let's assume I have three database tables: table_Main, table_sub_A, table_sub_B

"table_Main" fields:

  • RowID
  • Code (this field is used to find the "table_sub_" table
  • Name

Example "table_Main" rows:

1,A,Test A
2,B,Test B

Now, I want to build an SQL query which will retrieve all rows from table_Main but also get count(*) from corresponding tables for each table_Main row.

SELECT *, (SELECT COUNT(*) FROM table_sub_XXXX) AS TotalRecords  FROM table_Main

Problem starts here. XXXX should be the "Code" column value for each corresponding table_Main row. How can I generate a dynamic table name inside sub-select query?

Thanks for your help.

1 Answer 1

1

You can't

SELECT
   *,
   (SELECT COUNT(*) FROM table_sub_A) AS TotalRecordsA, 
   (SELECT COUNT(*) FROM table_sub_B) AS TotalRecordsB
FROM
   table_Main

However, MySQL may evaluate this per row of table_Main

So I'd do this to help the query optimiser

SELECT
   *, TotalRecordsA, TotalRecordsB 
FROM
   table_Main
   CROSS JOIN
   (SELECT COUNT(*) AS TotalRecordsA FROM table_sub_A) A
   CROSS JOIN
   (SELECT COUNT(*) AS TotalRecordsB FROM table_sub_B) B
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but there are 500+ tables that are linked to the main table based on "Code" column on table_main. Therefore, table name on sub-select query must be dynamically set. Any suggestions?
@Cem: not really. You'd have to PREPARE a dynamic SQL statement by querying INFORMATION_SCHEMA.TABLES. I leave that as an exercise for you...

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.