我有一个场景,我有一个主表。主表有 2 个额外列,一列用于表名称(子表名称),另一列用于表 id(子表 id)。当我们在主表中输入值时,我们还告诉在子表中输入值,然后我们在主表名称字段中输入表的名称,在主表的子字段中输入子id。
现在,当我查询时,我需要将查询与子表连接起来,方式是从列中获取表名称,并使用 concat 函数将查询与该表连接起来,然后连接子 id。
下面是表的结构以及值
CREATE TABLE IF NOT EXISTS `tbl` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`tbl_type` enum('multi','gift','pledge') DEFAULT NULL,
`tbl_type_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSERT INTO `tbl` (`id`, `timestamp`, `tbl_type`, `tbl_type_id`) VALUES
(1, '2015-03-09 09:39:42', '', 1),
(2, '2015-03-09 22:43:23', 'multi', 2),
(3, '2015-03-09 23:26:38', 'gift', 1),
(4, '2015-03-10 09:46:15', 'pledge', 2);
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tbl_gift` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amount` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `tbl_gift` (`id`, `amount`) VALUES
(1, '1231200'),
(2, '1231200');
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tbl_multi` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amount` float(255,0) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tbl_pledge` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amount` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `tbl_pledge` (`id`, `amount`) VALUES
(1, '10000'),
(2, '10200');
这是简单的硬代码查询
select * from tbl t left join tbl_gift g on g.id = t.tbl_type_id
但我想让它变得动态,我尝试了这个
select * from tbl t left join (concat('tbl', '_', t.tbl_type)) g on g.id = t.tbl_type_id
应该得到我需要的 table
(concat('tbl', '_', t.tbl_type))
但出现错误
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('tbl', '_', t.tbl_type)) g on g.id = t.tbl_type_id LIMIT 0, 30' at line 1
最佳答案
Ankit 和Usedby 的评论回答了您的问题。 SQL 不允许您按照您的尝试提供动态构造的表名称。他们为您提供了两个选项:1)在 PHP 端动态构建查询,然后 SQL 仅查看静态表名称或 2)使用SQL PREPARE命令构造动态表名并使用EXECUTE SQL命令执行它。
关于php - Mysql 查询连接表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29032408/