从一个表中获取数据列表,并从另一个表中获取一些记录数,是否可以在一个查询中执行?

发布于 2024-09-24 18:06:51 字数 633 浏览 3 评论 0原文

我有两个表 - countriestours

countries 有字段 (id),(name),(order)

tours有字段 (id),(id_country)...


我需要获取 idname 的完整列表> 来自按顺序排序的表 countries,以及表 tours 中的记录数,其中 tours.id_country = 国家.id 国家

即,我需要获取这样的列表

id   name      count_of_tours
1    France    15
2    England   22
.............................

是否可以在一个查询中完成?

非常感谢

I have two tables - countries, tours.

countries has fields (id),(name),(order)

tours has fields (id),(id_country)...


I need to get the whole list of id and name from table countries ordered by their order, and the count of records in table tours, where tours.id_country = countries.id countries.

Ie, i need to get such list

id   name      count_of_tours
1    France    15
2    England   22
.............................

Is it possible to do in one query?

Thanks much

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

思念绕指尖 2024-10-01 18:06:51
SELECT C.id,
       C.name,
       COUNT(T.id) as count_of_tours
  FROM countries C
  LEFT JOIN tours T
         ON T.id_country = C.id
 GROUP BY C.id,
          C.name
 ORDER BY C.order
SELECT C.id,
       C.name,
       COUNT(T.id) as count_of_tours
  FROM countries C
  LEFT JOIN tours T
         ON T.id_country = C.id
 GROUP BY C.id,
          C.name
 ORDER BY C.order
不知在何时 2024-10-01 18:06:51
SELECT countries.id, countries.name, COUNT(id_country) AS Count
FROM countries
LEFT JOIN tours
on tours.id_country = countries.id
GROUP BY id_country
ORDER BY countries.order
SELECT countries.id, countries.name, COUNT(id_country) AS Count
FROM countries
LEFT JOIN tours
on tours.id_country = countries.id
GROUP BY id_country
ORDER BY countries.order
溇涏 2024-10-01 18:06:51

这确实是可能的,您需要学习的只是连接的用法。使用连接时,您可以连接两个表的结果并将输出作为一个输出。

SELECT id, name, COUNT(id_country) FROM states LEFT JOINtours ontours.id_country =countries.id order bycountries.id;

This is real possible all you need to learn is the usage of joins. When you use join you can join the result from two tables and give the output as one.

SELECT id, name, COUNT(id_country) FROM countries LEFT JOIN tours on tours.id_country = countries.id order by countries.id;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文