我使用了如下查询
INSERT INTO `tbl_contact` (`fname`,`code`,`contact`,`m_address`,`created_date`,`modified_date`,`row_status`)
SELECT * FROM (SELECT 'LULU CENT','sdfjg','NA','NA',1991-01-01,1990-01-01,'active')
AS tmp WHERE NOT EXISTS (SELECT `id` FROM tbl_contact WHERE CODE='sdfjg') LIMIT 1
我得到以下
错误代码:1060 列名称重复' NA'
我的问题是我无法在数据库表的两列中添加相同的数据。
答案 0 :(得分:9)
当您选择常量值而不命名列时,如下所示
SELECT 'LULU CENT','sdfjg','NA'
返回结果的列名将与相应的列值相同,即第一列名称为LULU CENT
,第二列名称为sdfjg
,依此类推。< / p>
由于您的子查询是以下
SELECT 'LULU CENT','sdfjg','NA','NA',1991-01-01,1990-01-01,'active'
第三和第四列名称相同(NA
)。如果您将上述查询放在SELECT * FROM (...) AS tmp
这样的
SELECT * FROM
(
SELECT 'LULU CENT',
'sdfjg',
'NA',
'NA',
1991-01-01,
1990-01-01,
'active'
)
AS tmp
您需要为子查询中的每一列设置不同的名称,如下所示
INSERT INTO `tbl_contact`
(
`fname`,
`code`,
`contact`,
`m_address`,
`created_date`,
`modified_date`,
`row_status`
)
SELECT * FROM
(
SELECT
'LULU CENT' AS `fname`,
'sdfjg' AS `code`,
'NA' AS `contact`,
'NA' AS `m_address`,
1991-01-01 AS `created_date`,
1990-01-01 AS `modified_date`,
'active' AS `row_status`
)
AS tmp WHERE NOT EXISTS (SELECT `id` FROM tbl_contact WHERE CODE='sdfjg') LIMIT 1