gpt4 book ai didi

mysql - SQL查询建议请

转载 作者:行者123 更新时间:2023-11-30 01:02:21 24 4
gpt4 key购买 nike

我正在尝试编写一个 SQL 查询来计算许可证的价格。请检查下面的架构:

表:价格

| ID (bigint) | USERS(Bigint) |  TYPE (varchar) | PRICE (BIGINT)
------------------------------------------------------------------
| 1 | 1 | other | 20 |
| 2 | 15 | local | 13.96 |

表:许可证

| ID (bigint) | USERID (Bigint) |STATUS(VARCHAR) |  USERS(bigint) | DEVICES(BIGINT) | TYPE(VARCHAR) | REQUEST_TYPE (VARCHAR) | 
--------------------------------------------------------------------------------------------------------------
| 1 | 13 | 10 | 10 | local | add |
| 2 | 13 | 15 | 20 | other | extend |

我的目标:

给定用户 ID 和类型,我想根据以下条件计算所有许可证的总价格:

对于给定的用户 ID 和类型:

1) 获取 request_type 为新(或)扩展的所有许可证

2) 对于每个此类许可证,将用户数量(用户列)与“价格”表中的用户列进行匹配,并按设备进行计算*(价格表中的关联价格)

3) 使用此计算所有此类价格的总和并返回总价。

我尝试使用以下查询来执行此操作,但尚未成功:

SELECT SUM(PRICE) FROM prices
LEFT OUTER JOIN licenses
ON (
prices.users=licenses.users
AND prices.type=licenses.type
)
WHERE licenses.userid=13
AND licenses.status='approved'
AND licenses.request_type IN ('add','extend')

请在此处检查 SQL Fiddle:http://sqlfiddle.com/#!2/05f5cf

请帮忙。

谢谢,大卫

最佳答案

结果将为空,因为查询找不到 LEFT OUTER JOIN 的条件

有一个查询

SELECT SUM(PRICE) FROM prices
LEFT OUTER JOIN licenses
ON (
prices.users=licenses.users
AND prices.type=licenses.type //cannot found condition on table
)
WHERE licenses.userid=13
AND licenses.status='approved'
AND licenses.request_type IN ('add','extend')

这是表中的数据

表格许可证

(1, 'approved', 10, 10, 'local', 'add', 13),
(2, 'approved', 15, 20, 'other', 'extend', 13);

和表价格

(1, 1, 'other', 20),
(2, 15, 'local', 13.96);

你的情况是

  prices.users=licenses.users
AND prices.type=licenses.type //cannot found condition on table
that mean if from your table is

at licences table have a type="other" and users=15
but at prices table haven't have type="other" and users=15

所以结果将为空

因为当我更改第一行表格价格时 (1, 1, '其他', 20) 变成 (1, 15, '其他', 20),

结果 = 20

您需要更改查询的第一行

SELECT SUM(PRICE) FROM prices

be

SELECT IFNULL(SUM(PRICE),0) FROM prices

如果没有找到该行,这会将结果更改为 0 非空

关于mysql - SQL查询建议请,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19998957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com