告诉mySQL获取最少数量记录的最佳方式是什么?
假设我有一个产品表,我需要返回至少5个项目以适应网站设计。 我可以很容易地写出类似的东西:
SELECT *
FROM products
WHERE featured = true;
但如果这只返回3个结果,那么从数据库中返回另外2个产品的最佳方法是什么?我想也许是UNION
加入查询以返回几个随机产品。有没有人有任何进一步的建议?
答案 0 :(得分:2)
你可以使用ORDER BY + LIMIT来达到这个效果:
鉴于该数据集:
mysql> SELECT * FROM P;
+--------+----------+
| name | featured |
+--------+----------+
| Apple | 1 |
| Pear | 1 |
| Orange | 1 |
| Lime | 0 |
| Turnip | 0 |
| Salad | 0 |
+--------+----------+
6 rows in set (0.00 sec)
如你所见,还不够"特色"产品:
mysql> SELECT * FROM P WHERE featured = true LIMIT 5;
+--------+----------+
| name | featured |
+--------+----------+
| Apple | 1 |
| Pear | 1 |
| Orange | 1 |
+--------+----------+
3 rows in set (0.00 se
但是通过命令检索第一个特色,然后使用非特色产品达到极限,你就拥有了你想要的东西:
mysql> SELECT * FROM P ORDER BY featured DESC LIMIT 5;
+--------+----------+
| name | featured |
+--------+----------+
| Apple | 1 |
| Pear | 1 |
| Orange | 1 |
| Lime | 0 |
| Turnip | 0 |
+--------+----------+
5 rows in set (0.00 sec)