请查看此fiddle。
我正在处理搜索过滤器选择框,我想将表的字段名称作为行插入。
这是表格schemea:
CREATE TABLE general
(`ID` int, `letter` varchar(21), `double-letters` varchar(21))
;
INSERT INTO general
(`ID`,`letter`,`double-letters`)
VALUES
(1, 'A','BB'),
(2, 'A','CC'),
(3, 'C','BB'),
(4, 'D','DD'),
(5, 'D','EE'),
(6, 'F','TT'),
(7, 'G','UU'),
(8, 'G','ZZ'),
(9, 'I','UU')
;
CREATE TABLE options
(`ID` int, `options` varchar(15))
;
INSERT INTO options
(`ID`,`options`)
VALUES
(1, 'letter'),
(2, 'double-letters')
;
options
表中的ID字段充当外键,我想得到如下的输出并插入到新表中:
id field value
1 1 A
2 1 C
3 1 D
4 1 F
5 1 G
6 1 I
7 2 BB
8 2 CC
9 2 DD
10 2 EE
11 2 TT
12 2 UU
13 2 ZZ
我失败的尝试:
select DISTINCT(a.letter),'letter' AS field
from general a
INNER JOIN
options b ON b.options = field
union all
select DISTINCT(a.double-letters), 'double-letters' AS field
from general a
INNER JOIN
options b ON b.options = field
答案 0 :(得分:1)
很确定你想要这个:
select distinct a.letter, 'letter' AS field
from general a
cross JOIN options b
where b.options = 'letter'
union all
select distinct a.`double-letters`, 'double-letters' AS field
from general a
cross JOIN options b
where b.options = 'double-letters'
小提琴: http://sqlfiddle.com/#!2/bbf0b/18/0
要指出的事情,你不能加入列别名。因为您要别名的列是您选择的文字,所以您可以在WHERE子句中将该文字指定为条件。
你并没有真正加入GENERAL和OPTIONS之间的任何东西,所以你真正想要的是一个CROSS JOIN;您放入ON子句的条件实际上属于WHERE子句。
答案 1 :(得分:1)
我刚刚在Oracle上发了这个查询。 它工作并产生你描述的输出:
SELECT ID, CASE WHEN LENGTH(VALUE)=2THEN 2 ELSE 1 END AS FIELD, VALUE
FROM (
SELECT rownum AS ID, letter AS VALUE FROM (SELECT DISTINCT letter FROM general ORDER BY letter)
UNION
SELECT (SELECT COUNT(DISTINCT LETTER) FROM general) +rownum AS ID, double_letters AS VALUE
FROM (
SELECT DISTINCT double_letters FROM general ORDER BY double_letters)
)
它也应该在Mysql上运行。
我没有使用options
表。我不明白他的角色。对于这个例子,这种类型的输出似乎是不必要的
希望这可以帮到你。