mySQL删除具有count(*)GROUP和HAVING的行

时间:2019-02-20 09:13:54

标签: mysql sql having

我有这个查询,在这里我得到所有具有相同articleID和categoryID = 2153的重复条目 现在我要删除此行。但这似乎不直接起作用。 所以我尝试了子查询,但是当我使用IN时,我需要一个仅返回ID的子查询。但这也是不可能的。

如何从该查询中删除行?

SELECT id, articleID, categoryID, count(*) AS count 
FROM `s_articles_categories`
GROUP BY articleID
HAVING count(*) > 1 AND categoryID = 2153

3 个答案:

答案 0 :(得分:2)

假设id是表s_articles_categories的主键,则可以在子选择结果上使用联接。

要删除所有行:

delete  r.* 
from s_articles_categories r
INNER JOIN (
    SELECT id, articleID, categoryID, count(*) AS count FROM
    `s_articles_categories` r
    GROUP BY articleID
   HAVING count(*) > 1 AND categoryID = 2153

) t on t.id = r.id 

答案 1 :(得分:1)

如果要删除所有重复项,但在每个组中保留一个重复项,则可以使用以下查询:

DELETE FROM `s_articles_categories` s
WHERE s.categoryID = 2153 AND EXISTS (
    SELECT 1 
    FROM `s_articles_categories` s1
    WHERE s1.articleID = s.articleID AND s1.categoryID = s.categoryID AND s1.id < s.id
)

答案 2 :(得分:0)

我建议将其写为:

public void readCustomCharacteristic() {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    /*check if the service is available on the device*/
    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("UUID of service"));
    if(mCustomService == null){
        Log.w(TAG, "Custom BLE Service not found");
        return;
    }
    /*get the read characteristic from the service*/
    BluetoothGattCharacteristic mReadCharacteristic = mCustomService.getCharacteristic(UUID.fromString("UUID of characteristic"));
    if(mBluetoothGatt.readCharacteristic(mReadCharacteristic) == false){
        Log.w(TAG, "Failed to read characteristic");
    }
}

public void writeCustomCharacteristic(byte[] value) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    /*check if the service is available on the device*/
    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("UUID of service"));
    if(mCustomService == null){
        Log.w(TAG, "Custom BLE Service not found");
        return;
    }
    /*get the read characteristic from the service*/
    BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString("UUID of characteristic"));
    mWriteCharacteristic.setValue(value);
    if(mBluetoothGatt.writeCharacteristic(mWriteCharacteristic) == false){
        Log.w(TAG, "Failed to write characteristic");
    }
}