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

标签 php mysql

是否有 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/

相关文章:

php - 对于图片上传,我应该在MYSQL数据库中添加一个字段来检查,还是简单地使用PHP来检查图片是否存在?

php - 计算 CSV 列中相似值的数量

javascript - 在 MySQL 中保存(使用 JS 请求)和读取(使用 PHP)XML

java - 无法将带有准备好的语句的utf-8字符插入mysql

php - fatal error : Uncaught exception 'Zend_Db_Table_Exception'

PHP - 向用户发送文件

php - 如何在 Laravel 5.1 中显示保存成功消息?

mysql - 当枚举字段设置为无效值时,使 MySQL 默认为 NULL

mysql - 根据另一个表mysql的值在表中插入值

mysql&php - 无法执行存储过程两次