按顺序对表格进行排序?

时间:2019-11-14 08:24:50

标签: mysql sql database

我有一个包含5列的users表,idageis_premiumis_maleis_customer,其中{{1} }是主键。

我要做的第一句话是。该语句有可能返回0行:

id

然后仅从上述查询中获得的行中,我想找到年龄最大的人。

SELECT * FROM users
WHERE is_premium = 1 AND
is_name = 0 AND
is_customer = 0

问题:如何将这两个单独的SQL语句合并为一个语句,最有效的方法是什么?

3 个答案:

答案 0 :(得分:2)

为什么不直接:

SELECT *
FROM users
WHERE is_premium = 1 
AND is_name = 0 
AND is_customer = 0
ORDER BY age DESC, id ASC
LIMIT 1

对于mysql 8及更高版本,您还可以使用公用表表达式(CTE):

WITH D AS (
    SELECT * FROM users
    WHERE is_premium = 1 
    AND is_name = 0 
    AND is_customer = 0
)
SELECT * 
FROM D
WHERE AGE = (SELECT MAX(AGE) FROM D)
ORDER BY ID
LIMIT 1

答案 1 :(得分:1)

假设您有一个名为id的主键列,只需将查询移到子查询中即可:

SELECT *
FROM users
WHERE id = (
    SELECT id
    FROM users
    WHERE is_premium = 1 AND is_name = 0 AND is_customer = 0
    ORDER BY age DESC
    LIMIT 1
)

答案 2 :(得分:0)

假设您将有多个max()年龄相同的用户

select * from users t1
inner join (
    select max(age) maxage from users
    where is_premium=1 and is_name=0 and is_customer=0) t2
on t2.maxage = t1.age
where is_premium=1 and is_name=0 and is_customer=0

,如果您不想重复conditions

select * from users t1
inner join(
    select  
        (select max(t.age) from users t where t.id = t2.id) as maxage,
        t2.id
    from users t2 
    where is_premium=1 and is_name=0 and is_customer=0) t3 on t3.id = t1.id