小编典典

查询返回的行太少

sql

设置:

mysql> create table product_stock(
       product_id integer, qty integer);
Query OK, 0 rows affected (0.17 sec)

mysql> create table product(
       product_id integer, product_name varchar(255));
Query OK, 0 rows affected (0.11 sec)

mysql> insert into product(product_id, product_name) 
       values(1, 'Apsana White DX Pencil');
Query OK, 1 row affected (0.05 sec)

mysql> insert into product(product_id, product_name) 
       values(2, 'Diamond Glass Marking Pencil');
Query OK, 1 row affected (0.03 sec)

mysql> insert into product(product_id, product_name) 
       values(3, 'Apsana Black Pencil');
Query OK, 1 row affected (0.03 sec)

mysql> insert into product_stock(product_id, qty) 
       values(1, 100);
Query OK, 1 row affected (0.03 sec)

我的第一个查询:

mysql> SELECT IFNULL(SUM(s.qty),0) AS stock, 
              product_name 
       FROM product_stock s 
        INNER JOIN product p ON p.product_id=s.product_id 
       GROUP BY product_name 
       ORDER BY product_name;

返回:

+-------+---------------------------+ 
| stock | product_name              | 
+-------+---------------------------+ 
| 100   | Apsana White DX Pencil    | 
+-------+---------------------------+ 
1 row in set (0.00 sec)

但我想得到以下结果:

+-------+------------------------------+ 
| stock | product_name                 | 
+-------+------------------------------+ 
|   0   | Apsana Black Pencil          | 
| 100   | Apsana White DX Pencil       | 
|   0   | Diamond Glass Marking Pencil | 
+-------+------------------------------+

为了得到这个结果,我应该运行什么mysql查询?


阅读 173

收藏
2021-04-22

共1个答案

小编典典

您需要翻转连接并使用LEFT JOIN而不是INNER JOIN:

SELECT IFNULL(SUM(s.qty),0) AS stock, product_name
FROM product AS p
LEFT JOIN product_stock AS s ON p.product_id=s.product_id
GROUP BY product_name
ORDER BY product_name;
2021-04-22