Mysql查询(相同)返回不同结果集的不同结果顺序

时间:2014-10-20 12:27:25

标签: mysql

我对Mysql世界天真.... :)我试图使用连接从表中查询,

我遇到了结果集的问题......并且表结构是

...以下

VIDEO_XXXXX

| Field         | Type          | Null | Key | Default           | Extra                       |
| VIDEO_ID      | int(255)         
| TAG_NAME      | varchar(1000)
| SHOP_ID       | varchar(100)   FK
| LOVES          | int(255)      
| VIDEO_URL     | varchar(1000) 
| UPLOADED_DATE | 


PLACE_TABLE...

 SHOP_ID       | varchar(100) PK

查询看起来像..

   SELECT V.SHOP_ID
     FROM VIDEO_xxxx V  
     JOIN STUB_xxxx_TABLE S  ON S.SHOP_ID=V.SHOP_ID
    WHERE S.COUPON_STATUS='REDEEMED' 
 GROUP BY V.SHOP_ID 
 ORDER BY COUNT(S.COUPON_GENERATED_ID) DESC;

结果集如下......

+-----------+
| SHOP_ID   |
+-----------+
| 001       |
| 004       |
| 005       |
| 003       |
| 002       |

第二个问题是....

   SELECT V.SHOP_ID
     FROM SECOND_TABLE V  
     JOIN STUB_xxxx_TABLE S  ON S.SHOP_ID=V.SHOP_ID  
    WHERE S.COUPON_STATUS='REDEEMED'
 GROUP BY V.SHOP_ID 
 ORDER BY COUNT(S.COUPON_GENERATED_ID) DESC;

结果集是......

+--------+
| SHOP_ID|
+--------+
|001     |
|004     |
|003     |
|002     |
 005     |

我想知道为什么shop_id的顺序洗牌...... :( :(任何帮助都会受到赞赏...... :),

1 个答案:

答案 0 :(得分:0)

您可以将表达式COUNT(S.COUPON_GENERATED_ID)添加到where子句:

   SELECT V.SHOP_ID,COUNT(S.COUPON_GENERATED_ID)
     FROM SECOND_TABLE V  
     JOIN STUB_xxxx_TABLE S  ON S.SHOP_ID=V.SHOP_ID  
    WHERE S.COUPON_STATUS='REDEEMED'
 GROUP BY V.SHOP_ID 
 ORDER BY COUNT(S.COUPON_GENERATED_ID) DESC;

如果您不希望在结果中使用此额外值,则可以使用子查询:

 SELECT SHOP_ID
   FROM (
          SELECT V.SHOP_ID,COUNT(S.COUPON_GENERATED_ID) AS CNT
            FROM SECOND_TABLE V  
            JOIN STUB_xxxx_TABLE S  ON S.SHOP_ID=V.SHOP_ID  
           WHERE S.COUPON_STATUS='REDEEMED'
        GROUP BY V.SHOP_ID 
        )
ORDER BY CNT DESC