如何根据ID选择特定数据

时间:2019-02-02 19:50:37

标签: sql database

数据表

id  |  regiondId     |     provId    |    munId   |     brgyId   |   deleted
1   |      4         |       41      |     411    |     411001   |      1
2   |      4         |       41      |     411    |     411002   |      1
3   |      4         |       41      |     412    |     412001   |      0
4   |      4         |       41      |     412    |     412002   |      0 
5   |      4         |       41      |     413    |     413001   |      0
6   |      4         |       41      |     413    |     413002   |      0
7   |      4         |       41      |     414    |     414001   |      0
8   |      4         |       41      |     414    |     414002   |      1

样品我想选择在413 munId,但在此之前我可以选择413,我需要选择区域和第一省

这是我的查询,如下所示。

SELECT * 
FROM tbldata 
WHERE regionId = '4' 
    AND provId = '41' 
    AND munId = '413' 
    AND brgyId = '' 
    AND deleted != 1

因此1被删除而0不被删除 但是使用AND运算符会返回null,因为我的brgyId = null,并且如果我替换了AND运算符并在brgyId附近使用OR,即使已删除munId 413也会获取所有数据。

有一种方式来获得基于所述给定值的特定数据等,如果我

SELECT * 
FROM tbldata where regiondId = '4' 
    AND provId = '41' 
    AND munId = '413' 
    AND brgyId ='413001' 
    AND deleted = 1

我得到ID为5的数据,如果我

SELECT * 
FROM tbldata 
WHERE regiondId = '4' 
    AND provId = '41' 
    AND munId = '413' 
    AND brgyId = '' 
    AND deleted = 1

我得到ID为5和6的数据 如果我

SELECT * 
FROM tbldata 
WHERE regiondId = '4' 
    AND provId = '41' 
    AND munId = '' 
    AND brgyId = ''
    AND deleted = 1

我获得ID为1到8的数据

1 个答案:

答案 0 :(得分:0)

如果您不在乎某个列中的值,请仅在WHERE子句中不包括对该列的任何限制。

例如,获取具有id56的行:

SELECT *
       FROM tbldata
       WHERE regiondId = '4'
             AND provId = '41'
             AND munId = '413'
             AND deleted = 0;

请注意,brgyId子句中的WHERE上没有任何操作。

(如果列的数据类型实际上是数字类型,则还可以删除单引号。)