เมื่อต้องการนับจำนวนแถวรวมจากหลายตารางในคำสั่งเดียว สามารถใช้ UNION ALL รวมผลลัพธ์ COUNT(*) ของแต่ละตาราง แล้วใช้ SUM() นับรวม
ตัวอย่างการใช้งาน
สร้างตาราง 2 ตารางและเพิ่มข้อมูล:
mysql> create table DemoTable1 (Id int, Name varchar(30)); mysql> insert into DemoTable1 values(10,'Chris Brown'),(20,'David Miller'),(30,'John Adam'); mysql> create table DemoTable2 (Amount int); mysql> insert into DemoTable2 values(100),(200),(300);
ข้อมูลตารางแรก (3 แถว) และตารางที่สอง (3 แถว)
คำสั่งหาผลรวมจำนวนแถวทั้งสองตาราง
mysql> select sum(AllCount) AS Total_Count
-> from (
-> (select count(*) AS AllCount from DemoTable1)
-> union all
-> (select count(*) AS AllCount from DemoTable2)
-> ) t;
ผลลัพธ์
+-------------+ | Total_Count | +-------------+ | 6 | +-------------+
คำอธิบาย:
- Subquery แต่ละอันนับแถวของตารางตัวเองได้ค่า 3 และ 3
UNION ALLรวมผลลัพธ์ทั้งสอง (ไม่ลบซ้ำ)- Query ภายนอกใช้
SUM(AllCount)รวมเป็น 6 - ต้องตั้ง alias ให้ subquery (ที่นี่คือ
t) ตามกฎของ MySQL