MySql从已选择的数据中选择

时间:2015-11-09 21:27:51

标签: mysql sql having

您好我正在尝试从已选择的值中选择数据。

当前查询:

select t.ticket_num, t.item_id, t.trans_id
from tickets as t
inner join ticket_items as ti
on ti.id = t.item_id
where ti.online = 1
    and ti.bundle = 5
    and ti.type_id = 2

数据样本:

num   |   item    | tran
5699    1328    766
5700    1328    766
5701    1328    766
5702    1328    766
5703    1328    766
5704    1330    767
5705    1330    767
5706    1330    767
5707    1330    767
5708    1330    767
5709    1332    768
5710    1332    768
5711    1332    768
5712    1332    768
5713    1332    768
5714    1333    768
5715    1333    768
5716    1333    768
5717    1333    768
5718    1333    768
5719    1334    768
5720    1334    768
5721    1334    768
5722    1334    768
5723    1334    768
5724    1336    769
5725    1336    769
5726    1336    769
5727    1336    769
5728    1336    769
5729    1338    770
5730    1338    770
5731    1338    770
5732    1338    770
5733    1338    770
5734    1339    770
5735    1339    770
5736    1339    770
5737    1339    770
5738    1339    770
5739    1340    770
5740    1340    770
5741    1340    770
5742    1340    770

根据这些数据,我只想要在tran上有15个或更多项目的数据,你可以看到766只有5个,但768有15个,所以我希望这些数据中的所有数据都超过或等于15。

由于

1 个答案:

答案 0 :(得分:1)

执行子查询,查找所需查询中包含15个或更多记录的所有tran组(密钥使用GROUP BYHAVING子句)。然后在主查询中选择找到tran IN子查询的所有记录。例如:

select 
    t.ticket_num, t.item_id, t.trans_id 
from tickets as t
inner join ticket_items as ti
    on ti.id = t.item_id
where ti.online = 1
    and ti.bundle = 5
    and ti.type_id = 2
    and trans_id in 
    (select t.trans_id
        from tickets as t
        inner join ticket_items as ti
            on ti.id = t.item_id
        where ti.online = 1
            and ti.bundle = 5
            and ti.type_id = 2
        GROUP BY t.trans_id 
        HAVING count(t.trans_id)>=15
    )

您可以通过将冗余JOIN拉出到公用表表达式来清理它,如下所示:

WITH tquery as (SELECT * 
    from tickets
    inner join ticket_items as ti
        on ti.id = t.item_id
    where ti.online = 1
        and ti.bundle = 5
        and ti.type_id = 2
)
select 
    ticket_num, item_id, trans_id 
from tquery
where trans_id in 
    (select t.trans_id
        from tquery as t
        GROUP BY t.trans_id 
        HAVING count(t.trans_id)>=15
    )

如果你想知道它是如何运作的话,请参阅有关条款的更多内容:What's the difference between HAVING and WHERE?