2016-08-09 5 views
0

Ich habe die folgende Tabellenstruktur, die die Beziehung zwischen den Pfosten und ihre Kategorien definieren.Löschen mit mehreren wo auf verschiedenen Zeilen für die gleiche ID - MySQL

Post_id | Category_id 
--------------------- 
1  | A 
1  | B 
1  | C 
2  | A 
2  | B 
2  | C 
2  | D 

Deshalb möchte ich den Posten suchen, die zwei bestimmten Kategorien (zum Beispiel A und B) und löschen dann die Zeile A. So das Ergebnis wäre:

Post_id | Category_id 
--------------------- 
1  | B 
1  | C 
2  | B 
2  | C 
2  | D 

Wie kann Dies erreichen?

Antwort

1

starten:

delete t1 
from yourtable t1 
join (
    -- This sub query will retrieve records that have both A and B for each `Post_id` 
    select Post_id 
    from yourtable 
    where Category_id in ('A', 'B') 
    group by Post_id 
    having count(distinct Category_id) = 2 
) t2 
-- Then join this sub query on your table. 
on t1.Post_id = t2.Post_id 
where t1.Category_id = 'A' 

Demo Here

+0

als ks! es hat perfekt funktioniert. Was bedeuten t1 und t2? – Fosfor

+0

@Fosfor t1 und t2 sind nur Alias ​​für eine Tabelle. – Blank

0

Sie können die Beiträge finden, indem Sie:

select post_id 
from post_categories 
where category_id in ('A', 'B') 
group by post_id 
having count(distinct category_id) = 2; 

Sie können sie dann löschen mit einem join:

delete pc 
    from post_categories pc join 
     (select post_id 
      from post_categories 
      where category_id in ('A', 'B') 
      group by post_id 
      having count(distinct category_id) = 2 
     ) todelete 
     on pc.post_id = todelete.post_id 
    where pc.category_id = 'A';