Return default result for IN value regardless(返回 IN 值的默认结果,不管)
问题描述
我有一个查询,可以获取在某个日期范围内在线的所有用户.由于我想如何显示数据,这是通过 IN 查询完成的.但是,如果没有找到解析为 IN 条件的 ID 的记录,我想返回一个默认值.
I have a query that gets all user that have been online between a certain date range. This is done via an IN query due to how I want to display the data. However, I would like to return a default value if no records were found for an ID that was parsed into the IN condition.
简化查询:
SELECT users.Name, users.ID, SUM(users.Minutes) AS MinutesOnline
FROM UserTable
LEFT JOIN OnlineUseage ON OnlineUseage.ID = UserTable.ID
WHERE OnlineUseage.Date >= '2016-01-01 00:00:00' AND OnlineUseage.Date <= '2016-12-31 23:59:59'
AND UserTable.ID IN(332,554,5764,11,556,.........)
GROUP BY users.ID
ORDER BY FIELD(UserTable.ID, 332,554,5764,11,556,.........)
现在上面的查询将只拉入那些符合条件的行,正如预期的那样.我还希望查询为不满足条件的 IN 条件中的 ID 提取默认值.
Now the above query will only pull in those row that meet the condition, as expected. I would also like the query to pull in a default value for the ID's within the IN condition that don't meet the condition.
在这种情况下使用 IFNULL
将不起作用,因为记录永远不会返回
Using IFNULL
in this instance will not work as the record is never returned
SELECT users.Name, users.ID, IFNULL(SUM(users.Minutes), 0) AS MinutesOnline
FROM UserTable
LEFT JOIN OnlineUseage ON OnlineUseage.ID = UserTable.ID
WHERE OnlineUseage.Date >= '2016-01-01 00:00:00' AND OnlineUseage.Date <= '2016-12-31 23:59:59'
AND UserTable.ID IN(332,554,5764,11,556,.........)
GROUP BY users.ID
ORDER BY FIELD(UserTable.ID, 332,554,5764,11,556,.........)
仅供参考 - 我正在将此查询解析为自定义 PDO 函数.我没有使用过时的 mysql 函数
FYI - i'm parsing this query into a custom PDO function. I'm not using deprecated mysql functions
推荐答案
你有一个条件 OnlineUseage
左连接变成内连接.
You have a condition on OnlineUseage
the left join become like a inner join.
将您的条件移至 from
子句会更好:
move your condition to the from
clause will be better :
SELECT
users.Name,
users.ID,
IFNULL(SUM(users.Minutes), 0) AS MinutesOnline
FROM
users
LEFT JOIN OnlineUseage ON
OnlineUseage.ID = users.ID and
OnlineUseage.Date >= '2016-01-01 00:00:00' AND
OnlineUseage.Date <= '2016-12-31 23:59:59'
WHERE
users.ID IN (332,554,5764,11,556,.........)
GROUP BY
users.ID,users.Name
ORDER BY
users.ID
这篇关于返回 IN 值的默认结果,不管的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回 IN 值的默认结果,不管


基础教程推荐
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01