Mysql – Select Mysql Table based on other table field value


I wonder if its possible to make query like this one:

SELECT cs.platform,
     (SELECT COUNT(*) FROM general_list as loc WHERE loc.platform=cs.platform) as indexed,
     (SELECT COUNT(*) FROM cs.table     as loc WHERE loc.platform=cs.platform) as sandbox
    SELECT platform, table
    FROM states
    WHERE visible=1
) as cs

For each iteration in the main select, I need to take the table name from cs.table to info from such table.

Is there anyway to accomplish this?

Best Answer

The only way to "dynamically" use a tablename is via a Stored Routine in which you do CONCAT(...) to build the SQL, plus PREPARE and EXECUTE to then perform the constructed SQL.

Needing to do this is usually a sign of poor schema design. Please explain the schema and why you went that direction; we may be able to help 'fix' it.