我正在使用sqLite并具有两个表Profile和Option。配置文件的选项可能因代码而异(请参见下面的示例)。基本上,用户可以创建自定义配置文件,因此代码不同。
如何将配置文件选项拉入选项列表,以便只有一个输出?我唯一的关系是基于代码的,但是某些配置文件的代码未在选项中列出。我希望未包含在“选项”中的代码也要包括在内,并且不重复那些已存在的代码。
下面的代码请参阅我对预期输出的评论。
也在这里制造了一个小提琴。 http://sqlfiddle.com/#!5/3e657c/1/0
CREATE TABLE profile (id INTEGER PRIMARY KEY, profileId INTEGER, value integer, type text, "name" text, "min" integer, "max" integer, "justment" text, "sortOrder" INTEGER, "code", text);
INSERT INTO "profile" ("id", "profileId", "value", "type", "name", "code") VALUES
('1','1', '0', 'c', 'John', 'test_001'),
('2', '1','0', 'c', 'Peter', 'test_002'),
('3','1', '0', 'c', 'Custom Record', 'cust_003');
CREATE TABLE options (id INTEGER PRIMARY KEY , value integer, type text, "name" text, "min" integer, "max" integer, "justment" text, "sortOrder" INTEGER DEFAULT 0, "code" text);
INSERT INTO "options" ("id", "value", "type", "name", "code") VALUES
('1', '0', 'c', 'John', 'test_001'),
('2', '0', 'c', 'Peter', 'test_002'),
('3', '0', 'c', 'Paul', 'test_003'),
('4', '0', 'c', 'Tim', 'test_004');
预期输出单个列表,无重复
|Name|
John
Peter
Paul
Tim
Custom Record
/*
不确定这是否可行,但请多加理解。可能必须使用PHP中的循环来执行此操作,但是如果有任何SQL方法,将不胜感激。
答案 0 :(得分:1)
您可以在第二个查询中使用UNION ALL
和NOT EXISTS
来做到这一点:
select id, value, type, name, code from options
union all
select id, value, type, name, code from profile p
where not exists (
select 1 from options o
where p.code = o.code
)
您可以更改select
列表以返回所需的列。
请参见demo。
结果:
| id | value | type | name | code |
| --- | ----- | ---- | ------------- | -------- |
| 1 | 0 | c | John | test_001 |
| 2 | 0 | c | Peter | test_002 |
| 3 | 0 | c | Paul | test_003 |
| 4 | 0 | c | Tim | test_004 |
| 3 | 0 | c | Custom Record | cust_003 |