假設(shè)有一個用戶表(d_user):
CREATE TABLE IF NOT EXISTS `d_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增id',
`name` varchar(50) NOT NULL COMMENT '用戶名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='用戶表';
用戶數(shù)據(jù)如下:
mysql> select * from d_user;
+----+--------+
| id | name |
+----+--------+
| 1 | 張三 |
| 2 | 李四 |
+----+--------+
2 rows in set (0.00 sec)
一個訂單表(d_order):
CREATE TABLE IF NOT EXISTS `d_order` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增id',
`user_id` bigint(20) NOT NULL COMMENT '用戶id',
`status` tinyint(1) default 0 NOT NULL COMMENT '訂單狀態(tài) 1:已支付 0:待支付',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='訂單表';
訂單數(shù)據(jù)如下:
mysql> select * from d_order;
+----+---------+--------+
| id | user_id | status |
+----+---------+--------+
| 1 | 1 | 1 |
+----+---------+--------+
1 row in set (0.00 sec)
假如需要查詢用戶已支付訂單數(shù)量:
第一種寫法:
mysql> SELECT
-> d_user.NAME,
-> count( d_order.id ) AS total
-> FROM
-> d_user
-> LEFT JOIN d_order ON d_order.user_id = d_user.id
-> WHERE
-> d_order.STATUS = 1
-> GROUP BY
-> d_user.id;
+--------+-------+
| NAME | total |
+--------+-------+
| 張三 | 1 |
+--------+-------+
1 row in set (0.00 sec)
第二種寫法:
mysql> SELECT
-> d_user.NAME,
-> count( d_order.id ) AS total
-> FROM
-> d_user
-> LEFT JOIN d_order ON d_order.user_id = d_user.id
-> AND d_order.STATUS = 1
-> GROUP BY
-> d_user.id;
+--------+-------+
| NAME | total |
+--------+-------+
| 張三 | 1 |
| 李四 | 0 |
+--------+-------+
2 rows in set (0.00 sec)
總結(jié):
聯(lián)表時條件放在WHERE后面,條件會影響主表返回條數(shù)料饥;
聯(lián)表時條件放在ON后面索烹,條件不會影響主表返回條數(shù);