【问题标题】:How to apply the where clause of the whole query on the sub-queries also?如何将整个查询的 where 子句也应用于子查询?
【发布时间】:2014-01-11 09:01:08
【问题描述】:

我有以下 SQL 查询:

SELECT users.username, users.id, count(tahminler.tahmin)as tahmins_no, m.winnings
FROM users 
LEFT JOIN tahminler ON users.id = tahminler.user_id 
LEFT JOIN matches_of_comments ON tahminler.match_id = matches_of_comments.match_id
LEFT JOIN  (SELECT user_id ,count(result) as winnings from tahminler WHERE result = 1 group by user_id) as m ON m.user_id = users.id
WHERE (MONTH( STR_TO_DATE( matches_of_comments.match_date,  '%d.%m.%Y' ) ) =  01 AND YEAR( STR_TO_DATE( matches_of_comments.match_date,  '%d.%m.%Y' ) ) =  2014 AND flag=1)
GROUP BY users.id 
having count(tahminler.tahmin) > 0

Where 子句不适用于子查询 (m) 。我不想在子查询中添加相同的子句,这会使查询变得复杂且未优化。有没有办法在子查询中应用这个条件而不在子查询中重复它

【问题讨论】:

    标签: mysql sql database subquery query-optimization


    【解决方案1】:

    您的查询无需将同一个表连接两次。你可以从下面的查询中得到结果。

    试试这个:

    SELECT u.username, u.id, COUNT(t.tahmin) AS tahmins_no, 
           SUM(t.result = 1) AS winnings
    FROM users u 
    LEFT JOIN tahminler t ON u.id = t.user_id 
    LEFT JOIN matches_of_comments mc ON t.match_id = mc.match_id
    WHERE MONTH(STR_TO_DATE(mc.match_date, '%d.%m.%Y')) = 1 AND 
          YEAR(STR_TO_DATE(mc.match_date, '%d.%m.%Y')) = 2014 AND flag=1
    GROUP BY u.id 
    HAVING tahmins_no > 0
    

    【讨论】:

    • 就像魅力一样。但是为什么你用 sum 而不是 count?
    • @Basel 不客气……你想要结果为 1 的用户。你可以用 SUM(t.result = 1)SUM(CASE t.result WHEN 1 THEN 1 ELSE 0 END) 来做到这一点,两者都是一样的
    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多