如何在一个查询上运行这两行

时间:2014-06-28 13:56:08

标签: mysql sql

我有一个具有这种结构的表

Name    Type    Collation   Attributes  Null    Default Extra   Action
 1  user_id int(11)         No          None         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 2  amount  decimal(16,8)   No          None         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 3  aff int(11)             No             0         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 4  jackpot int(11)         No             0         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 5  paidout int(11)         No             0         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 6  type    int(11)         No             0         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 7  created timestamp       No   CURRENT_TIMESTAMP   Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More

我在同一个查询中尝试了这两行而没有成功:

UPDATE `trans` where paidout=1 GROUP BY user_id
UPDATE `trans`where paidout=0 GROUP BY user_id

也只是为了查看不更新会很好

像这样

SELECT * FROM  `trans` where paidout=1 GROUP BY user_id
SELECT * FROM  `trans` where paidout=0 GROUP BY user_id

我需要在同一个查询上运行这两行

我需要按user_id对表行进行分组,但是相同的user_id在某些行中的paidout = 1,而在其他一些行中的paidout = 0

所以我想按user_id进行分组,其中paidout = 1,GROUP BY user_id,其中paidout = 0

所以我会为每个user_id获得2行

2 个答案:

答案 0 :(得分:0)

从你给我们的小东西狂野猜测你想要的东西:

SELECT user_id,paidout,count(*),sum(amount) FROM trans GROUP BY user_id,paidout

答案 1 :(得分:0)

如果您只想查看Paidout = 0和Paidout = 1的所有记录,您需要执行以下操作:

SELECT * from `trans` WHERE paidout = 1

SELECT * from `trans` WHERE paidout = 0

或(如果你想要两者)

SELECT * from `trans` WHERE paidout = 1 OR paidout = 0

只有在想要使用聚合函数(Sum,Average,Max,Min等)时才需要Group By子句。

如果您想要运行聚合函数(例如,如果您想要paidout = 1和0的记录数),那么您将执行以下操作:

SELECT paidout, count(paidout) FROM `trans` GROUP BY paidout

我希望这已经解决了您的问题,如果没有,请回复更多详情,我会更新此答案!

注意:这些只是运行这些查询的最基本方法,您可以根据自己的需要进一步调整和优化它们,但这超出了这个答案的范围!