MYSQL 有报表和计算问题
MYSQL HAVING STATEMENT AND CALCULATION ISSUE
这个 mySQL 语句有什么问题?
我检查 C_BATCH_ID 在 batch table 然后将其与从引用中提取的值进行比较 (C_KEY)
它 returns 什么都没有,如果我将 MAX( C_BATCH_ID ) 替换为 23它returnsn条记录.
SELECT
contract.KEY AS C_KEY,
contract.BATCH_ID AS C_BATCH_ID,
contract.CUSTOMER_NAME as C_NAME,
batch.BATCH_ID = B_BATCH_ID
FROM
contract
INNER JOIN
batch ON contract.BATCH_ID = batch.BATCH_ID
HAVING
SUBSTRING_INDEX( C_KEY, '-', 1 ) = MAX( B_BATCH_ID )
ORDER BY
contract.CUSTOMER_NAME
感谢您的帮助。 :)
合同table
id
C_KEY
C_BATCH_ID
C_NAME
1
10-KEY01
10
Customer 1
2
23-KEY01
23
Customer 2
3
23-KEY02
23
Customer 3
4
12-KEY01
12
Customer 2
5
23-KEY03
23
Customer 4
批量table
B_BATCH_ID
BATCH_NAME
1
Batch 1
2
Batch 2
3
Batch 3
4
Batch 4
10
Batch 10
12
Batch 12
23
Batch 23
期望的结果,因为 23 是 B_BATCH_ID 的最大值:
id
C_KEY
C_BATCH_ID
C_NAME
B_BATCH_ID
2
23-KEY01
23
Customer 2
23
3
23-KEY02
23
Customer 3
23
5
23-KEY03
23
Customer 4
23
您需要在子查询中获取 MAX(BATCH_ID)
。解决方案可能是这样的:
SELECT
contract.KEY AS C_KEY,
contract.BATCH_ID AS C_BATCH_ID,
contract.CUSTOMER_NAME as C_NAME
FROM
contract
WHERE
SUBSTRING_INDEX( contract.KEY, '-', 1 ) = (SELECT MAX(BATCH_ID) FROM batch)
ORDER BY
contract.CUSTOMER_NAME
基于示例数据 contract.BATCH_ID
可以用来代替 SUBSTRING_INDEX( contract.KEY, '-', 1 )
但不确定在实际数据中是否有这样做的原因
这个 mySQL 语句有什么问题?
我检查 C_BATCH_ID 在 batch table 然后将其与从引用中提取的值进行比较 (C_KEY)
它 returns 什么都没有,如果我将 MAX( C_BATCH_ID ) 替换为 23它returnsn条记录.
SELECT
contract.KEY AS C_KEY,
contract.BATCH_ID AS C_BATCH_ID,
contract.CUSTOMER_NAME as C_NAME,
batch.BATCH_ID = B_BATCH_ID
FROM
contract
INNER JOIN
batch ON contract.BATCH_ID = batch.BATCH_ID
HAVING
SUBSTRING_INDEX( C_KEY, '-', 1 ) = MAX( B_BATCH_ID )
ORDER BY
contract.CUSTOMER_NAME
感谢您的帮助。 :)
合同table
id | C_KEY | C_BATCH_ID | C_NAME |
---|---|---|---|
1 | 10-KEY01 | 10 | Customer 1 |
2 | 23-KEY01 | 23 | Customer 2 |
3 | 23-KEY02 | 23 | Customer 3 |
4 | 12-KEY01 | 12 | Customer 2 |
5 | 23-KEY03 | 23 | Customer 4 |
批量table
B_BATCH_ID | BATCH_NAME |
---|---|
1 | Batch 1 |
2 | Batch 2 |
3 | Batch 3 |
4 | Batch 4 |
10 | Batch 10 |
12 | Batch 12 |
23 | Batch 23 |
期望的结果,因为 23 是 B_BATCH_ID 的最大值:
id | C_KEY | C_BATCH_ID | C_NAME | B_BATCH_ID |
---|---|---|---|---|
2 | 23-KEY01 | 23 | Customer 2 | 23 |
3 | 23-KEY02 | 23 | Customer 3 | 23 |
5 | 23-KEY03 | 23 | Customer 4 | 23 |
您需要在子查询中获取 MAX(BATCH_ID)
。解决方案可能是这样的:
SELECT
contract.KEY AS C_KEY,
contract.BATCH_ID AS C_BATCH_ID,
contract.CUSTOMER_NAME as C_NAME
FROM
contract
WHERE
SUBSTRING_INDEX( contract.KEY, '-', 1 ) = (SELECT MAX(BATCH_ID) FROM batch)
ORDER BY
contract.CUSTOMER_NAME
基于示例数据 contract.BATCH_ID
可以用来代替 SUBSTRING_INDEX( contract.KEY, '-', 1 )
但不确定在实际数据中是否有这样做的原因