使用sql从数据库中选择数据

时间:2017-01-18 16:01:27

标签: php html mysql sql

我有一个sql子选择列出有多少订单及其总价值:

SELECT u.name,
  (SELECT COUNT(*) FROM orders o WHERE o.user_id=u.id
  ) AS order_count,
  (SELECT SUM(oi.quantity * p.price)
  FROM orders            AS o
  INNER JOIN order_items AS oi
  ON oi.order_id = o.id
  INNER JOIN products AS p
  ON p.id        = oi.product_id
  WHERE o.user_id=u.id
  ) AS total_price
FROM users u
ORDER BY total_price DESC

任何想法如何在没有子选择的情况下做到这一点?

3 个答案:

答案 0 :(得分:0)

您可以使用Left Join

SELECT u.NAME,
       AS order_count,
       total_price
FROM   users u
       LEFT JOIN (SELECT Count(*) AS order_count,
                         user_id
                  FROM   orders
                  GROUP  BY user_id) p
              ON o.user_id = u.id
       LEFT JOIN (SELECT Sum(oi.quantity * p.price) AS total_price,
                         o.user_id
                  FROM   orders AS o
                         INNER JOIN order_items AS oi
                                 ON oi.order_id = o.id
                         INNER JOIN products AS p
                                 ON p.id = oi.product_id
                  GROUP  BY o.user_id) so
              ON so.user_id = u.id
ORDER  BY total_price DESC 

答案 1 :(得分:0)

您可以将相关子查询(O(N ^ 2)性能)转换为LEFT JOIN

SELECT u.name,
  o.order_count,
  o2.total_price
FROM users u left join (
  SELECT user_id, COUNT(*) order_count
  FROM orders
  GROUP BY user_id
) o
on u.id = o.user_id
left join (
  SELECT o.user_id, SUM(oi.quantity * p.price) total_price
  FROM orders o
  INNER JOIN order_items oi
  ON oi.order_id = o.id
  INNER JOIN products p
  ON p.id        = oi.product_id
  GROUP BY o.user_id
) o2 on u.id = o2.user_id
ORDER BY total_price DESC;

答案 2 :(得分:0)

这是与一个子查询相同的查询(注意没有测试语法,但你明白了):

select u.name, count(*) orderCount, sum(totalOrder) total order
  from users u
         join (select userid, o.id, sum(oi.quantity * p.price) totalorder
                from orders o
                    join order_items as oi on oi.order_id = o.orderid
                    join products p on oi.product_id = p.id
                group by userid, o.id) x
on u.id = x.user_id
group by u.name