从两个表中选择SELECT MAX返回一个奇怪的值

时间:2017-11-03 11:11:35

标签: mysql

Table 'orders'   
    +----+-------+
    | id | refId |
    +----+-------+
    |  3 | 3     |
    |  7 | 5     |
    |  8 | 200   |
    |  9 | NULL  |
    | 10 | NULL  |
    | 21 | NULL  |
    +----+-------+

Table 'transactions'
    +----+-------+
    | id | refId |
    +----+-------+
    | 23 |   200 |
    | 24 |   201 |
    | 22 |   202 |
    | 26 |   203 |
    | 25 |   204 |
    | 27 |   205 |
    +----+-------+

所以我得到了这两个表,我想获得refId的最大值(即205)

我正在使用的是下一个查询:

SELECT MAX( cacat ) 
FROM (

    SELECT refId AS cacat
    FROM orders
    UNION 
    SELECT refId AS cacat
    FROM transactions

    ) AS pla

- >>返回

+------------+
| MAX(cacat) |
+------------+
|          5 |
+------------+

感谢任何帮助,谢谢!

3 个答案:

答案 0 :(得分:0)

获得所需结果的一种方法是将文本refId值转换为数字:

SELECT MAX( cacat ) 
FROM
(
    SELECT CAST(refId AS UNSIGNED) AS cacat FROM orders
    UNION ALL
    SELECT CAST(refId AS UNSIGNED) FROM transactions
) AS pla

注意:文字不是数字,数字不是文字。如果您确实需要refId列的行为类似于数字,那么可以考虑将此信息存储在某种MySQL数字列中。

Demo

答案 1 :(得分:0)

尝试:

SELECT MAX( cast(cacat as unsigned) ) 
FROM (

    SELECT refId AS cacat
    FROM orders
    UNION 
    SELECT refId AS cacat
    FROM transactions

    ) AS pla

答案 2 :(得分:0)

WITH abc AS ( SELECT refId FROM orders

UNION

SELECT refId FROM transactions

abc

中选择最大值(refId)