2015-03-13 119 views
0

我有一個場景,我有一個主表。主表有兩個額外的列,一個是表名(子表名),另一個是表ID(子表ID)。當我們在主表中輸入值時,我們也告訴子表中的輸入值,然後我們在主表名字段中輸入表的名稱,在主表的子字段中輸入子標識。Mysql查詢加入表列

現在,當我查詢我需要連接查詢與子表的方式,我從列中選取表名稱,並與該表與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 
+1

嘗試準備聲明? – 2015-03-13 12:37:05

+0

除非創建動態SQL,否則您不能在SQL中執行此操作[''''''''''''在PHP中構建查詢字符串可能更有意義。 – 2015-03-13 12:39:30

+0

@AnkitSharma,你的意思是什麼,請你解釋 – Iori 2015-03-13 16:04:08

回答

1

通過ANKIT和Usedby的意見回答了你的問題。 SQL不允許您按照您嘗試的方式提供動態構建的表名稱。他們爲您提供了兩種選擇:1)在PHP端動態構建您的查詢,然後SQL僅查看靜態表名或2)使用SQL PREPARE命令構造動態表名和執行它的EXECUTE SQL命令。