MySQL 查询 : LIMITing a JOIN

标签 mysql sql join greatest-n-per-group

假设我有两个要加入的表。 分类:

id   name
----------
1    Cars
2    Games
3    Pencils

和项目:

id   categoryid   itemname
---------------------------
1    1            Ford
2    1            BMW
3    1            VW
4    2            Tetris
5    2            Pong
6    3            Foobar Pencil Factory

我想要一个返回类别和第一个(且仅是第一个)项目名称的查询:

category.id category.name item.id item.itemname
-------------------------------------------------
1           Cars          1       Ford
2           Games         4       Tetris
3           Pencils       6       Foobar Pencil Factory

有什么方法可以得到随机结果,例如:

category.id category.name item.id item.itemname
-------------------------------------------------
1           Cars          3       VW
2           Games         5       Pong
3           Pencils       6       Foobar Pencil Factory

谢谢!

最佳答案

刚刚做了一个快速测试。这似乎有效:

mysql> select * from categories c, items i
    -> where i.categoryid = c.id
    -> group by c.id;
+------+---------+------+------------+----------------+
| id   | name    | id   | categoryid | name           |
+------+---------+------+------------+----------------+
|    1 | Cars    |    1 |          1 | Ford           |
|    2 | Games   |    4 |          2 | Tetris         |
|    3 | Pencils |    6 |          3 | Pencil Factory |
+------+---------+------+------------+----------------+
3 rows in set (0.00 sec)

我认为这可以满足您的第一个问题。不确定第二个 - 我认为它需要一个带有 order by random() 或类似东西的内部查询!

关于MySQL 查询 : LIMITing a JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/163004/

相关文章:

mysql - 通过创建表关系我会看到性能提升吗?

MySql 与 SQL-Server 的性能问题

python - 从 MySQL 语句获取结果并存储在 Python 列表中并检查条件

php - 如何显示 "minutes ago"而不是 posted_time 的 UTC 时间?

android - 您如何开始使用 Google Cloud SQL?

c++ - 在 MySQL/Connector C++ 中使用 SQL 连接

mysql - MySQL 中的右外连接

mysql - 选择 JOINed 子串

c# - 尝试使用 asp.net 更新数据库时出现异常错误

sql - 操作数类型冲突 : date is incompatible with smallint error in sql server