MySQL连接三个表

时间:2014-04-05 07:20:37

标签: mysql sql

我有三个表:产品,请求,预订。

Table Products (with all product categories):
name, ..
A1, ..
A1, ..
A2, ..
A2, ..
A2, ..
A3, ..
B1, ..
..

Table Requests (with a state for every request):
name, failed 
A1, 0
A2, 1
A3, 0
A2, 0
..

Table Bookings:
name, ..
A1, ..
A2, ..
..

我需要的是带有这样的摘要数据的连接输出:

prod_category, count_requests, count_failed, count_bookings
A1, 1, 0, 1
A2, 2, 1, 1
A3, 6, 0, null
B1, null, null, null

我已经有三个单独的查询 - 它们运行良好,但我无法仅使用一个查询。

以下是我的一个SQL查询示例:

SELECT
    T2.n AS category_name, T1.c AS count_requests
FROM
    (SELECT
       object_name as n,
       count(object_name) as c
    FROM
       requests
    GROUP BY n) T1
    RIGHT JOIN
    (SELECT distinct
       object_name as n
    FROM
       products) T2 ON T1.n = T2.n
ORDER BY T2.n ASC;

查询输出:

# category_name, count_requests
'A1', '8'
'A2', '3'
'C1', NULL
'E1', '9'
'E2', '16'
'E3', '3'
'F1', '1'

3 个答案:

答案 0 :(得分:2)

假设所有不会失败的请求也会导致预订中的一行,则根本不需要加入预订。

select p.name, 
      count(r.name) as count_requests, 
      sum(r.failed) as count_failed,
      count(r.name) - sum(r.failed) as count_bookings
  from products p
  left join requests r on (p.name = r.name)
 group by p.name;

http://sqlfiddle.com/#!2/da461/6

答案 1 :(得分:1)

SELECT
  Name, 
  (SELECT COUNT(name) FROM Requests WHERE name = Products.Name) AS count_requests,
  (SELECT COUNT(name) FROM Requests WHERE name = Products.Name AND failed = 1) AS count_failed,
  (SELECT COUNT(name) FROM Requests WHERE name = Products.Name AND failed = 0) AS count_bookings
FROM Products
GROUP BY Name
ORDER BY Name

答案 2 :(得分:0)

我认为这应该可行,但它没有经过测试......

 SELECT products.name, COUNT(requests.name) AS count_requests, SUM(requests.failed) AS 
 fails, COUNT(bookings.name) AS bookings FROM products LEFT JOIN requests ON 
 products.name=requests.name LEFT JOIN bookings ON products.name=bookings.name 
 GROUP BY products.name ORDER BY products.name