如何从不同的子查询中收集多个值

时间:2017-10-08 18:03:28

标签: sql sqlite

我需要从几个表中获取一些统计信息:

我有工人,命令和约会。

如何在一个查询中完成:

1. SELECT count(id) AS TotalWorkers FROM workers;
2. SELECT w.name AS BestWorker FROM orders AS o LEFT JOIN workers AS w ON pe_id=w.id GROUP BY pe_id ORDER BY count(o.id) DESC LIMIT 1
3. SELECT count(id) AS OrdersPerformed FROM orders WHERE pe_id=1;
4. SELECT count(id) AS OrdersAccepted FROM orders WHERE ac_id=1;
5. SELECT post AS LastAppointment FROM appointments AS a LEFT JOIN posts AS p ON post_id=p.id WHERE worker_id=1 ORDER BY date DESC LIMIT 1;

如何将它们收集成一个大问题?

1 个答案:

答案 0 :(得分:2)

一种简单的方法是将select放在前面:

SELECT (SELECT count(id) FROM workers) AS TotalWorkers,
       (SELECT w.name FROM orders AS o LEFT JOIN workers AS w ON pe_id=w.id GROUP BY pe_id ORDER BY count(o.id) DESC LIMIT 1) as BestWorker,
       . . .