MySQL查询使用内部联接从表中检索数据

时间:2012-10-08 04:18:52

标签: mysql join

这两个表FruitFruit_types。两个表之间有am:n关系,所以我们有第三个表fruit_type_fruit,它有上面的主键two tables {1}}。表格看起来像这样

Fruit
ID    NAME    
1    A
2    B
3    C

Fruit_type
ID    LABEL
1    CITRIC
2    DRUPES
3    UNCATALOGUED

Fruit_type_Fruit
Fruit_id    Fruit_type
1        1
1        2
1        3
2        1
3        3

问题陈述:即使他们有一个类别(即标签),一些水果也会被标记为Uncatalogued

例如: -         A获得以下标签:柠檬酸,核果和未编目。

    B has    citric ,

    C has    Uncatalogued. 

现在我需要一个查询来删除所有具有合适标签但仍具有未编目标签的记录。 在上面的例子中

A record which is uncatalogued should be deleted and not

A    Citric and    Drupes neither

C    Uncatalogued. 

1 个答案:

答案 0 :(得分:2)

这样的事情

SQL Fiddle DEMO

DELETE ftf
FROM fruit_type_fruit ftf
WHERE Fruit_type_ID = 3
AND Fruit_ID IN
    (
            SELECT *
            FROM (
                    SELECT DISTINCT Fruit_ID
                    FROM fruit_type_fruit f 
                    WHERE f.Fruit_type_ID = 3
             ) ss
            WHERE Fruit_ID IN (
                    SELECT *
                    FROM (
                    SELECT DISTINCT Fruit_ID
                    FROM fruit_type_fruit f 
                    WHERE f.Fruit_type_ID <> 3
             ) s)
  )