【发布时间】:2015-03-13 12:34:52
【问题描述】:
我有一个场景,我有一个主表。主表有 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
应该得到我需要的桌子
(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
【问题讨论】:
-
试过准备语句?
-
您不能在 SQL
unless you create dynamic SQL中执行此操作 [left join (concat('tbl', '_', t.tbl_type))]。在 PHP 中构造查询字符串可能更有意义。 -
@AnkitSharma,你是什么意思,你能解释一下
-
不同的情况,不同的反应。应该有一个评论过滤器:D