SQL - EXISTS / NOT EXISTS函数

时间:2016-04-16 09:49:36

标签: sql function exists

我正在尝试学习SQL,而且我在这里遇到了一些麻烦。

 ID  |  P_Id |  room | 
======================
 1   |   8   |   A   |
 2   |   8   |   A   |
 3   |   8   |   B   |
 4   |   9   |   B   |
 5   |   9   |   B   |
 6   |   10  |   C   |
 7   |   10  |   C   |
 8   |   10  |   D   |

我试图找出哪个P_Id只有 在B会议室工作。所以结果将是P_Id = 9。不是8,因为他也在A房工作。

这是我的查询,但它不起作用:

SELECT Room.P_Id
FROM Room
WHERE NOT EXISTS (SELECT *
                  FROM Room
                  WHERE Room.room <> 'B');

你们能帮助我吗?

4 个答案:

答案 0 :(得分:2)

您需要将子查询与外部查询相关联,并在外部和内部查询中使用不同的别名,否则子查询将使用错误的表。相关性确保子查询适用于外部查询中的正确行(P_Id匹配的位置)。

请改为:

SELECT DISTINCT r1.P_Id
FROM Room r1
WHERE NOT EXISTS (
  SELECT *
  FROM Room r2
  WHERE r2.room <> 'B'
    AND r1.P_Id = r2.P_Id
);

答案 1 :(得分:0)

这个怎么样:

Select Room.P_Id
FROM Room
WHERE MIN(room.room) = MAX(room.room) and MIN(room.room) = 'B'
Group by Room.P_Id

可能还有其他更优雅的方式,但这将完成工作。

答案 2 :(得分:0)

试试这个

Select distinct p_ID 
from room 
where room = 'B' 
  and p_id not in (Select p_ID from room where room <> 'B')

答案 3 :(得分:0)

您也可以尝试

        private async void Studijski_program_Load(object sender, EventArgs e)
    {
        await LoadDataSources();
        UpdateDisplay(false);

        //Filter();
    }

    private async Task LoadDataSources()
    {
        //visual stuff
        sTUDIJSKIPROGRAMBindingNavigator.Visible = false;
        nastavniPlanProgramsDataGridView.Visible = false;
        panel1.Visible = false;

        //detail datasource (this is left datagridview
        nastavniPlanProgramsBindingSource.DataSource = await master.NastavniPlanPrograms.AsNoTracking().ToListAsync();


        ///some code for comboboxes in datagridview not to cause error
        List<Predmet> predmeti = await master.Predmets.AsNoTracking().ToListAsync();
        predmeti.Insert(0, new Predmet
        {
            idPredmet = 0,
            nazivPredmet = "--Odaberi Predmet--"
        });
        predmetBindingSource.DataSource = predmeti;

        List<VRSTAIZVODJENJAPREDMETA> vrsta = await master.VRSTAIZVODJENJAPREDMETAs.AsNoTracking().ToListAsync();
        vrsta.Insert(0, new VRSTAIZVODJENJAPREDMETA
        {
            idVrIzvodPred = 0,
            Vrsta = "--Odaberite Vrstu--"
        });
        vRSTAIZVODJENJAPREDMETABindingSource.DataSource = vrsta;
        ///

        //master datasource (left datagridview) This one is causing problem
        await master.STUDIJSKIPROGRAMs.OrderBy(d => d.idStudProg).LoadAsync();
        sTUDIJSKIPROGRAMBindingSource.DataSource = master.STUDIJSKIPROGRAMs.Local.ToBindingList();



        //visual stuff
        sTUDIJSKIPROGRAMBindingNavigator.Visible = true;
        nastavniPlanProgramsDataGridView.Visible = true;
        panel1.Visible = true; 


    }