根据条件再选择一个表并在条件中添加

时间:2013-06-13 12:17:58

标签: mysql

SELECT a.id,
       a.username,
       a.email,
       a.created,
       b.user_id,
       SUM(b.price) + 
       SUM(IF(d.beginner =0, 15, 0)) + CASE WHEN SUM(b.price) >499 THEN 100
                                            ELSE 0 END AS points,
       SUM(b.price) AS pris,
       b.created,
       c.user_id,
       c.referrer_id,
       c.created,
       d.id,
       d.beginner,
       d.winner_id
FROM users a,
     accounts b,
     referrals c,
     product d
WHERE a.created BETWEEN '2013-04-01' AND '2013-06-30'
  AND d.created BETWEEN '2013-06-01' AND '2013-06-30'
  AND b.created BETWEEN '2013-06-01' AND '2013-06-30'
  AND a.id = b.user_id
  AND a.id = c.user_id
  AND d.winner_id = a.id
GROUP BY c.referrer_id
ORDER BY `points` DESC LIMIT 0 , 3

在这个查询中,我有四个表。使用product表我希望它也可以根据created进行选择。但是,当我喜欢我在查询中所做的事情时,它没有给我正确的结果。我想用这个查询选择产品表,其中条件是我只需要从6月1日到6月30日选择记录,并根据在产品表中找到赢家的情况下添加15个点的条件。

如果你看到这个SUM( IF( d.beginner =0, 15, 0 ) )条件,那么如果我不添加AND d.created BETWEEN '2013-06-01' AND '2013-06-30'并且如果用户在产品表中找不到用户,但是从两个条件的其余部分得到点数为30个点,则它不起作用显示此查询。我不知道为什么? 我想要从6月1日到6月30日以及4月1日到6月30日的桌面用户选择产品和帐户表

    SELECT a.id, a.username, a.email, a.created, b.user_id, SUM( b.price ) + 
CASE WHEN SUM( b.price ) >499
THEN 100 
ELSE 0 
END AS gr, SUM( b.price ) AS pris, b.created, c.user_id, c.referrer_id, c.created
FROM users a, accounts b, referrals c
WHERE a.created
BETWEEN  '2013-04-01'
AND  '2013-06-30'
AND b.created
BETWEEN  '2013-06-01'
AND  '2013-06-30'
AND a.id = b.user_id
AND a.id = c.user_id
GROUP BY c.referrer_id
ORDER BY  `gr` DESC 
LIMIT 0 , 3

我已经从中删除了产品表条件。所以现在很容易理解。我想添加表products,其中只选择从6月1日到30日的行,如果用户在winner_id列的产品表中找到,则第二个条件是添加15个点。

1 个答案:

答案 0 :(得分:0)

您的意见建议在该范围内的产品表中找不到记录。如果你仍然希望在这种情况下返回一行,那么使用LEFT OUTER JOIN。如下所示: -

SELECT a.id,
       a.username,
       a.email,
       a.created,
       b.user_id,
       SUM(b.price) + 
       SUM(CASE WHEN d.beginner IS NULL THEN 0 WHEN d.beginner = 0 THEN 15 ELSE 0 END) + CASE WHEN SUM(b.price) >499 THEN 100
                                            ELSE 0 END AS points,
       SUM(b.price) AS pris,
       b.created,
       c.user_id,
       c.referrer_id,
       c.created,
       d.id,
       d.beginner,
       d.winner_id
FROM users a
INNER JOIN accounts b ON a.id = b.user_id
INNER JOIN referrals c ON a.id = c.user_id
LEFT OUTER JOIN product d ON d.winner_id = a.id AND d.created BETWEEN '2013-06-01' AND '2013-06-30'
WHERE a.created BETWEEN '2013-04-01' AND '2013-06-30'
  AND b.created BETWEEN '2013-06-01' AND '2013-06-30'
GROUP BY c.referrer_id
ORDER BY `points` DESC 
LIMIT 0 , 3