2017-06-17 91 views
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 

我如何可以做同樣的與不同量列的兩個表?

+1

https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql - 查詢 – Yunnosch

回答

1

如果您填寫了缺失的列,例如
(例如),則可以使用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是字符串' - '的整數類比。

+0

這有幫助,謝謝。 – Dezork

相關問題