0
我有两张桌子。如何从两个不相关的表sqlite中获取数据?
table_1: id, title, img_url, url, gif_url, date
table_2: id, title, url, date
现在我只能从表1的数据是这样
SELECT * FROM table_1 ORDER BY date DESC LIMIT 10
我如何可以做同样的与不同量列的两个表?
我有两张桌子。如何从两个不相关的表sqlite中获取数据?
table_1: id, title, img_url, url, gif_url, date
table_2: id, title, url, date
现在我只能从表1的数据是这样
SELECT * FROM table_1 ORDER BY date DESC LIMIT 10
我如何可以做同样的与不同量列的两个表?
如果您填写了缺失的列,例如
(例如),则可以使用UNION ALL
。通过插入常量值(如字符串' - ',假设您的网址是文本)。
SELECT * FROM table_1
UNION ALL
SELECT id, title, '-' as img_url, url, '-' as gif_url, date FROM table_2
ORDER BY date DESC LIMIT 10;
如果有MCVE可用,测试将会容易得多。
我以此为(希望基本上等同)MCVE基础:
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE table_1 (a int, b int, c int);
INSERT INTO table_1(a,b,c) VALUES(1,5,7);
INSERT INTO table_1(a,b,c) VALUES(2,10,14);
CREATE TABLE table_2 (a int, c int);
INSERT INTO table_2(a,c) VALUES(3,11);
INSERT INTO table_2(a,c) VALUES(6,22);
COMMIT;
而结构相同的测试代码:
select * from table_1
UNION ALL
select a, 42 as b, c from table_2
order by a LIMIT 3;
给出的输出:
a b c
-------------------- ---------- ----------
1 5 7
2 10 14
3 42 11
注从table_2开始,从“3”开始,包含42而不是“b”。 42是字符串' - '的整数类比。
这有帮助,谢谢。 – Dezork
https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql - 查询 – Yunnosch