gpt4 book ai didi

php - MYSQL使用第二个表从第一个表中排序数据

转载 作者:行者123 更新时间:2023-11-29 05:44:46 25 4
gpt4 key购买 nike

是否有 MYSQL 查询可用于从第二个表中订购商品。

我的例子我正在列出我的商店...每个商店在不同的表格中都有许多产品。所以我的商品详情显示了该商店的产品数量..

是否有一个简单的 MYSQL 查询,以便我可以按产品数量订购我的商店

我的商店没有数字值,它计算第二个表中的行

最佳答案

如果我对你的问题的理解正确,你可能想尝试如下操作:

SELECT     stores.id store_id, COUNT(products.id) num_products
FROM stores
LEFT JOIN products ON (stores.id = products.store_id)
GROUP BY stores.id
ORDER BY num_products;

测试用例:

CREATE TABLE stores (id int, name varchar(10));
CREATE TABLE products (id int, store_id int);

INSERT INTO stores VALUES (1, 'store 1');
INSERT INTO stores VALUES (2, 'store 2');
INSERT INTO stores VALUES (3, 'store 3');
INSERT INTO stores VALUES (4, 'store 4');

INSERT INTO products VALUES (1, 1);
INSERT INTO products VALUES (2, 1);
INSERT INTO products VALUES (3, 1);

INSERT INTO products VALUES (4, 2);

INSERT INTO products VALUES (5, 3);
INSERT INTO products VALUES (6, 3);

结果:

+----------+--------------+
| store_id | num_products |
+----------+--------------+
| 4 | 0 |
| 2 | 1 |
| 3 | 2 |
| 1 | 3 |
+----------+--------------+
4 rows in set (0.00 sec)

您还可以通过在 ORDER BY num_products 之后添加 DESC 来按降序排序:

+----------+--------------+
| store_id | num_products |
+----------+--------------+
| 1 | 3 |
| 3 | 2 |
| 2 | 1 |
| 4 | 0 |
+----------+--------------+
4 rows in set (0.00 sec)

关于php - MYSQL使用第二个表从第一个表中排序数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3364416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com