1

我有两张桌子

+------+--------------+--------+----------+
| bkey | bname        | nochap | b_id     |
+------+--------------+--------+----------+
|    1 | Let Us C     |     17 | luc13    |
|    2 | OOP with C++ |     17 | oopwcpp6 |
+------+--------------+--------+----------+

卢克13

+------+-----------------+---------+
| cnum | cname           | c_id    |
+------+-----------------+---------+
|    1 | Getting Started | luc13gs |
|    2 | C Instructions  | luc13ci |
+------+-----------------+---------+

因此,如您所见,第二个表(luc13 )的表名是第一个表book的元素。所以在显示第二个表时,我不想指定它的名称,所以我编写了查询

SELECT * FROM (SELECT b_id FROM book WHERE bkey = 1)

并显示错误,

ERROR 1248 (42000): 每个派生表都必须有自己的别名

所以我搜索它并再次编写查询

SELECT * FROM (SELECT b_id FROM book WHERE bkey = 1 AS custom)

现在错误已删除,但输出仍然是

+-------+
| b_id  |
+-------+
| luc13 |
+-------+

所以我认为只有SELECT b_id FROM book WHERE bkey = 1被执行。那么有什么方法可以在不直接指定其名称的情况下显示我的表luc13吗?

4

1 回答 1

4

您必须为此使用 a prepared statement

SET @s := CONCAT('SELECT * FROM ', (SELECT b_id FROM book WHERE bkey = 1));

PREPARE stmt FROM @s;

EXECUTE stmt;

DEALLOCATE PREPARE stmt;
于 2016-06-21T12:29:05.867 回答