按列ID选择行,如果包含null,则包含另一列中包含相同值的行

时间:2018-08-16 17:59:16

标签: mysql

我正在尝试通过ID获取一行,但还要在其他列中包含具有相同值的行,但如果值是null或为空,则不包括它们。

数据:

+------+------+------+
|ID     GROUP |AREA  |
+------+------+------+
| 1    | A    | AA   |
+------+------+------+
| 2    |      | AA   |
+------+------+------+
| 3    | A    | AA   |
+------+------+------+
| 4    | B    | AA   |
+------+------+------+
| 5    |      | BB   |
+------+------+------+
| 6    | A    | AA   |
+------+------+------+
| 7    | B    | BB   |
+------+------+------+
| 8    |      | AA   |
+------+------+------+

我现在所拥有的:

SELECT * WHERE ID = 1 AND AREA = "AA"

哪个返回:

+------+------+------+
| 1    | A    | AA   |
+------+------+------+

但是我也想获取所有包含GROUP“ A”的行:

+------+------+------+
| 1    | A    | AA   |
+------+------+------+
| 3    | A    | AA   |
+------+------+------+
| 6    | A    | AA   |
+------+------+------+

但是如果“ GROUP”列为Null,则只需返回请求的ID。

SELECT * WHERE ID = 2 AND AREA = "AA"

+------+------+------+
| 2    |      | AA   |
+------+------+------+

我已经尽力想了一切。不同的联接和子查询,但是我似乎无法完成这项工作。

4 个答案:

答案 0 :(得分:0)

我不确定我是否完全了解您,但是如果您想获得ID的{​​{1}},也许您可​​以尝试

GROUP

答案 1 :(得分:0)

您可以尝试在子查询中写入条件,然后通过子查询进行自联接。

JOINAREA列上的GROUP条件,如果GROUPnull的附加项,则检查id

CREATE TABLE T(
  ID INT,
  `GROUP` VARCHAR(5),
  AREA VARCHAR(5)
);


INSERT INTO T VALUES ( 1 , 'A' , 'AA' );
INSERT INTO T VALUES ( 2 , NULL , 'AA' );
INSERT INTO T VALUES ( 3 , 'A' , 'AA' );
INSERT INTO T VALUES ( 4 , 'B' , 'AA' );
INSERT INTO T VALUES ( 5 , NULL , 'BB' );
INSERT INTO T VALUES ( 6 , 'A' , 'AA' );
INSERT INTO T VALUES ( 7 , 'B' , 'BB' );
INSERT INTO T VALUES ( 8 , NULL , 'AA' );

查询1

SELECT t1.* 
FROM T t1 INNER JOIN (
  SELECT * 
  FROM T 
  WHERE ID = 2 AND AREA = "AA"
) t2 ON t1.AREA = t2.AREA and t1.GROUP = t2.GROUP or (t2.GROUP is null and t1.id = t2.id)

Results

| ID |  GROUP | AREA |
|----|--------|------|
|  2 | (null) |   AA |

查询2

SELECT t1.* 
FROM T t1 INNER JOIN (
  SELECT * 
  FROM T 
  WHERE ID = 1 AND AREA = "AA"
) t2 ON t1.AREA = t2.AREA and t1.GROUP = t2.GROUP or (t2.GROUP is null and t1.id = t2.id)

Results

| ID | GROUP | AREA |
|----|-------|------|
|  1 |     A |   AA |
|  3 |     A |   AA |
|  6 |     A |   AA |

答案 2 :(得分:0)

尝试一下:

SELECT * FROM `table_name` WHERE `ID` = 2 AND `AREA` = 'AA' AND `GROUP` IN (SELECT `GROUP` FROM `table_name` WHERE `ID` = 2);

PS:请不要忘记从您要从中获取记录的表更改table_name

答案 3 :(得分:0)

我会和UNION一起做

SELECT
     ID
    ,`GROUP`
    ,AREA
FROM
    your_table
WHERE ID = 2
UNION
SELECT
    ID
    ,`GROUP`
    ,AREA
FROM
    your_table
WHERE
    `GROUP` = (SELECT `GROUP` FROM your_table WHERE ID = 2)
    AND NULLIF(`GROUP`, '') IS NOT NULL;