簡體   English   中英

從具有不同列數的兩個表中選擇*

[英]select * from two tables with different # of columns

如何從兩個不同的表中選擇不同的列,例如:

SELECT username, email FROM `table1` 
UNION
 SELECT * FROM `table2` WHERE username = 'user1';

我收到錯誤"#1222 - The used SELECT statements have a different number of columns" 根據我的理解,UNION不起作用,

有沒有辦法實現這一點,因為我需要不等數量的列和行, 並且兩個表中沒有相互/相似的條目(即user1未在table1中列出)?

這可以不在一個查詢中完成嗎?

謝謝!

您可以使用別名fake丟失的列 - 例如

 SELECT username, email, '' as name FROM `table1` 
 UNION
 SELECT username, email, name FROM `table2` 
 WHERE username = 'user1';

name在table2中,但不在table1中

除非你將UNIONS與JOINS混淆:

SELECT table1.*, table2.* FROM
table1 INNER JOIN table2
ON table1.username = table2.username

這會合並兩個表,因此您可以獲得同一行中的所有列。

如果兩個表中沒有相互或類似的條目,則這些條目應該是兩個不同的select語句。

SELECT username, email FROM `table1`;


SELECT * FROM `table2` WHERE username = 'user1';

這樣做的動機是什么?

table2的條目是否與table1相關? join會更合適嗎?

SELECT t1.username, t1.email, t2.*
FROM table1 t1
    JOIN table2 t2 ON t1.username = t2.username
WHERE t1.username = 'user1';

在列數較少的表中,請嘗試

SELECT *, 0 as col1, 0 as col2, ...

等,以使它們的列數相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM