Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

เลือกชื่อตารางเป็นคอลัมน์ใน UNION SELECT ของ MySQL

ใช้ค่าคงที่พร้อม AS ในแต่ละ SELECT แล้ว UNION รวมกัน

ตัวอย่าง

mysql> create table DemoTable ( Name varchar(20) );
Query OK, 0 rows affected (0.56 sec)
mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.18 sec)
mysql> create table DemoTable2 ( Name varchar(20) );
Query OK, 0 rows affected (0.59 sec)
mysql> insert into DemoTable2 values('Bob'); Query OK, 1 row affected (0.20 sec)

UNION พร้อมชื่อตาราง

mysql> select 'DemoTable' as DemoTable, Name from DemoTable union select 'DemoTable2' as DemoTable2, Name from DemoTable2;
+--------------+------+
| DemoTable    | Name |
+--------------+------+
| DemoTable    | John |
| DemoTable2   | Bob  |
+--------------+------+

วิธีนี้ช่วยระบุแหล่งที่มาของข้อมูลเมื่อรวมจากหลายตาราง