使用子查询值作为表名

时间:2013-05-15 16:02:59

标签: mysql

这是一个问题,对我来说不符合我的预期。这是查询

SELECT  `table_name` 
FROM    `category` 
WHERE   `id` = ( SELECT `category_id` 
                 FROM    `assets` 
                 WHERE   `id` = '24028'  )

返回我需要用作表名的值photos

enter image description here

我需要检索最终值。所以我这样使用它:

SELECT * 
FROM   ( 
         SELECT  `table_name` 
         FROM    `category` 
         WHERE   `id` =  ( SELECT `category_id` 
                           FROM   `assets` 
                           WHERE `id` = '24028'
                          )
       )

但是这会返回错误

  

#1248 - 每个派生表都必须有自己的别名

所以,就像使用它一样,

SELECT * 
FROM  (
        SELECT `table_name` 
        FROM   `category` 
        WHERE  `id` = (  SELECT `category_id` 
                         FROM   `assets` 
                         WHERE  `id` = '24028' )
       ) as `photos`

但它再次返回与上一张图像相同的值。但我期待的是它应该返回值:

SELECT * FROM `photos`

其中photos是子查询返回的值。

2 个答案:

答案 0 :(得分:3)

从外观上看,您正在尝试使用动态“FROM”表名构建查询。执行此操作的唯一方法是在代码中构建SQL,或使用预准备语句:

DELIMITER //; 
SET @s := CONCAT('SELECT * FROM ', (SELECT  `table_name` FROM `category` WHERE `id` = (SELECT `category_id` FROM `assets` WHERE `id` = '24028'));

PREPARE stmt FROM @s;

EXECUTE stmt;

DEALLOCATE PREPARE stmt;
//

答案 1 :(得分:0)

然后根据您的评论答案,如果您只处理一个可能的“table_name”,为什么不直接加入

select 
      A.ID,
      A.Category_ID,
      C.Category,
      TP.*
   from
      assets A
         JOIN Category C
            on A.ID = C.ID
         JOIN tbl_photo TP
            on A.ID = TP.ID
   where
      A.ID = '24028'