我正在寻找通过变量动态选择不同列名的查询。
假设我有包含我想要选择的“动态列”,如下所示:
SELECT `ObjectID`,`ObjectLabel` FROM `modules_forms_objects`
+----------+---------------+ | ObjectID | ObjectLabel | +----------+---------------+ | 71 | Join Date | | 72 | Active | +----------+---------------+
现在,我还有一个表,它是由上面的“ObjectID”调用的列。这里:
SELECT `data_id`,`71`,`72` FROM `7`
+---------+---------------------+------+ | data_id | 71 | 72 | +---------+---------------------+------+ | 1 | 0000-00-00 00:00:00 | NULL | +---------+---------------------+------+
我想在第一个表中加入一个“值”列,这个'包含来自的值 匹配第二个表中的列。 (例如:对于ObjectID#72,该值将为NULL)。
最终,我希望我的结果是这样的:
+----------+---------------+--------------------+ | ObjectID | ObjectLabel | Value | +----------+---------------+--------------------+ | 71 | Join Date |0000-00-00 00:00:00 | | 72 | Active | NULL | +----------+---------------+--------------------+
当我使用传统的“JOIN”时,我得到了每行的所有列,看起来有点沉重。
有什么想法吗?非常感谢!
答案 0 :(得分:1)
基本静态查询可能如下所示
SELECT m.ObjectID, m.ObjectLabel, q.Value
FROM modules_forms_objects m LEFT JOIN
(
SELECT objectid,
CASE objectid
WHEN 71 THEN `71`
WHEN 72 THEN `72`
END value
FROM `7` t CROSS JOIN
(
SELECT 71 objectid UNION ALL
SELECT 72
) c
) q
ON m.objectid = q.objectid
我们的想法是先展开您的7
表格,然后将其加入modules_forms_objects
输出:
| OBJECTID | OBJECTLABEL | VALUE | -----------|-------------|---------------------| | 71 | Join Date | 0000-00-00 00:00:00 | | 72 | Active | (null) |
这是 SQLFiddle 演示
如果7
表中没有几十列,我建议坚持使用静态查询。
现在与动态SQL相同
SET @sql = NULL, @sql1 = NULL, @sql2 = NULL;
SELECT GROUP_CONCAT(
CONCAT('WHEN ''', column_name, ''' THEN `', column_name, '`')
SEPARATOR ' ')
INTO @sql1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = SCHEMA()
AND table_name = '7'
AND column_name LIKE '7%'
GROUP BY table_name;
SELECT GROUP_CONCAT(
CONCAT('SELECT ''', column_name, ''' objectid' )
SEPARATOR ' UNION ALL ')
INTO @sql2
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = SCHEMA()
AND table_name = '7'
AND column_name LIKE '7%'
GROUP BY table_name;
SET @sql = CONCAT(
'SELECT m.ObjectID, m.ObjectLabel, q.Value
FROM modules_forms_objects m LEFT JOIN
(
SELECT objectid,
CASE objectid ', @sql1, ' END value
FROM `7` t CROSS JOIN
(', @sql2, '
) c
) q
ON m.objectid = q.objectid');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
这是 SQLFiddle 演示
答案 1 :(得分:0)
USE SHOW COLUMNS FROM tab_name
并使用FIELD属性获取相应的列。
答案 2 :(得分:0)
这将在特定表中提供所有列名称
SELECT
GROUP_CONCAT(COLUMN_NAME)
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
table_name = 'mytable'