Mysql 内连接和空精度舍入
我正在尝试对两个表执行内部联接,以便可以按照与另一个表中该值的 pid 关联的精度对值进行舍入。但是,它为 pid 3 返回 NULL。我相信这与 pid 2 的 NULL 精度有关,因为当我将其精度设置为非 NULL 值时,我在下面的查询中得到了 pid 3 的正确值。
如何重构此查询,以便即使另一个 pid 包含 NULL 精度,它也始终返回正确的值?
select pid_values.pid, pid_values.value, round(value, pids.precision)
from pid_values inner join pids on pid_values.pid = pids.pid;
+------+--------+------------------------------+
| pid | value | round(value, pids.precision) |
+------+--------+------------------------------+
| 1 | 10.123 | 10 |
| 2 | 5.5 | 6 |
| 3 | 3.1234 | NULL |
+------+--------+------------------------------+
两个表中的数据:
select * from pids;
+------+-----------+
| pid | precision |
+------+-----------+
| 1 | 0 |
| 2 | NULL |
| 3 | 1 |
+------+-----------+
select * from pid_values
+----+------+--------+
| id | pid | value |
+----+------+--------+
| 1 | 1 | 10.123 |
| 2 | 2 | 5.5 |
| 3 | 3 | 3.1234 |
+----+------+--------+
I am attempting to perform an inner join on two tables so that I can round a value by the precision associated with that value's pid in the other table. However, it is returning NULL for pid 3. I believe it has to do with the NULL precision for pid 2, because when I set it's precision to a non-NULL value, I get the correct value for pid 3 in the query below.
How can I restructure this query so that it will always return the correct value even if another pid contains a NULL precision?
select pid_values.pid, pid_values.value, round(value, pids.precision)
from pid_values inner join pids on pid_values.pid = pids.pid;
+------+--------+------------------------------+
| pid | value | round(value, pids.precision) |
+------+--------+------------------------------+
| 1 | 10.123 | 10 |
| 2 | 5.5 | 6 |
| 3 | 3.1234 | NULL |
+------+--------+------------------------------+
Data in both tables:
select * from pids;
+------+-----------+
| pid | precision |
+------+-----------+
| 1 | 0 |
| 2 | NULL |
| 3 | 1 |
+------+-----------+
select * from pid_values
+----+------+--------+
| id | pid | value |
+----+------+--------+
| 1 | 1 | 10.123 |
| 2 | 2 | 5.5 |
| 3 | 3 | 3.1234 |
+----+------+--------+
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试这个查询:
Try this query:
不要将 NULL 传递给 round。试试这个:
Hck 似乎有和我有同样的想法,但实现方式不同。当
precision IS NULL
时,我将让结果返回NULL
(如您的示例所示,并且与precision =0
不同),而他会四舍五入为整数。选择最适合您需求的内容。Don't pass NULL to round. Try this instead:
Hck seems to have had the same idea as me, but the implementations differ. When
precision IS NULL
, I'll have the result returnNULL
(as in your example, and to differ fromprecision =0
), while he'll round to an integer instead. Choose whatever suits your needs best.