[英]MYSQL - Get all records that have more than 1 record for the same id
[英]Get all records from more than one table with the same columns
我的數據庫中有3個表,這3個表具有公共列。 第1列是Name
,第2列是printed
,第3列是location
。
我想做的是從那3個表中獲取所有記錄
where printed = "NO" and location = "Submitted"
就像是
select *
from table1, table2, table3
where printed = "NO" and Location = "Submitted"
這可以嗎?
您可以使用union
來實現結果。 Union
追加單獨查詢的結果集:
select name, printed, location from table1 where printed = "NO" and Location = "Submitted"
union
select name, printed, location from table2 where printed = "NO" and Location = "Submitted"
union
select name, printed, location from table3 where printed = "NO" and Location = "Submitted"
如果您想知道特定記錄來自哪個表,請向每個查詢添加一個常量字段:
select name, printed, location, "table1" as table_name from table1 where printed = "NO" and Location = "Submitted"
...
如果所有三個表都具有相同的結構:
select t1.*
from table1 t1
where printed = 'NO' and Location = 'Submitted'
union
select t2.*
from table2 t2
where printed = 'NO' and Location = 'Submitted'
union
select t3.*
from table3 t3
where printed = 'NO' and Location = 'Submitted'
如果結構不同(即每個表中的不同列):
select t1.somecolumn, t1.someothercolumn, t1.etc
from table1 t1
where printed = 'NO' and Location = 'Submitted'
union
select t2.somecolumn, t2.someothercolumn, t2.etc
from table2 t2
where printed = 'NO' and Location = 'Submitted'
union
select t3.somecolumn, t3.someothercolumn, t3.etc
from table3 t3
where printed = 'NO' and Location = 'Submitted'
聯合必須返回相同數據類型的列,並以所選順序(由第一個選擇項定義的順序)返回它們。如果有重復項, UNION
將刪除它們。 如果要保留重復項,請改用UNION ALL
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.