0

我有以下查询,其中我使用了JOINs. 它说:

未知列 m.bv ..

你能看看并告诉我我做错了什么吗?

$query4 =  'SELECT u.*, SUM(c.ts) AS total_sum1, SUM(m.bv) AS total_sum 
FROM users u 
LEFT JOIN 
 (SELECT user_id ,SUM(points) AS ts FROM coupon GROUP BY user_id) c 
 ON u.user_id=c.user_id 
LEFT JOIN 
 (SELECT user_id ,SUM(points) AS bv FROM matching GROUP BY user_id) r 
ON u.user_id=m.user_id 
where u.user_id="'.$_SESSION['user_name'].'"
GROUP BY u.user_id';
4

3 回答 3

1

您正在SUM(points) AS bv从具有别名的表中选择r,没有具有别名的表m。所以它必须是r.bv这样的:

SELECT 
  u.*, 
  SUM(c.ts) AS total_sum1, 
  SUM(r.bv) AS total_sum 
FROM users u 
LEFT JOIN 
(
    SELECT 
      user_id,
      SUM(points) AS ts 
    FROM coupon 
    GROUP BY user_id
) c ON u.user_id=c.user_id 
LEFT JOIN 
(
    SELECT 
      user_id,
      SUM(points) AS bv 
     FROM matching 
     GROUP BY user_id
) r ON u.user_id = m.user_id 
where u.user_id="'.$_SESSION['user_name'].'"
GROUP BY u.user_id
于 2012-12-03T13:25:09.623 回答
0

将 m. 替换为 r。看第二个加入

于 2012-12-03T13:26:07.590 回答
0

您已使用 为派生表起别名,r并使用 引用该表(两次)m。纠正一个或另一个。

由于您user_id在两个子查询中分组并且user_id(我假设)是 table 的主键user,因此您实际上并不需要 final GROUP BY

如果它适用于所有(许多)用户,我会这样写:

SELECT u.*, COALESCE(c.ts, 0) AS total_sum1, COALESCE(m.bv, 0) AS total_sum 
FROM users u 
LEFT JOIN 
 (SELECT user_id, SUM(points) AS ts FROM coupon GROUP BY user_id) c 
   ON u.user_id = c.user_id 
LEFT JOIN 
 (SELECT user_id, SUM(points) AS bv FROM matching GROUP BY user_id) m  
   ON u.user_id = m.user_id

在您的(一个用户)案例中就像这样:

SELECT u.*, COALESCE(c.ts, 0) AS total_sum1, COALESCE(m.bv, 0) AS total_sum 
FROM users u 
  LEFT JOIN 
     (SELECT SUM(points) AS ts FROM coupon
      WHERE user_id = "'.$_SESSION['user_name'].'") c 
    ON TRUE 
  LEFT JOIN 
     (SELECT SUM(points) AS bv FROM matching
      WHERE user_id = "'.$_SESSION['user_name'].'") m
   ON TRUE 
WHERE u.user_id = "'.$_SESSION['user_name'].'"

最后一个查询也可以简化为:

SELECT u.*, 
     COALESCE( (SELECT SUM(points) FROM coupon 
                WHERE user_id = u.user_id)
             , 0) AS total_sum1,
     COALESCE( (SELECT SUM(points) FROM matching 
                WHERE user_id = u.user_id)
             , 0) AS total_sum 
FROM users u 
WHERE u.user_id = "'.$_SESSION['user_name'].'"
于 2012-12-03T13:31:37.540 回答