这是我的表
jobs (
depaermentid,
empid,
department
)
我插入了属于同一部门的空值
我喜欢检索值而不是null属于同一部门的其他值
1|1|
1|2|it
2|1|
2|2|cs
结果喜欢
1|1|it
1|2|it
我试过了这个查询
select gepartmentid,empId,department from from jobs group bt department;
答案 0 :(得分:0)
尝试:
mysql> DROP TABLE IF EXISTS `jobs`;
Query OK, 0 rows affected (0.01 sec)
mysql> CREATE TABLE IF NOT EXISTS `jobs` (
-> `depaermentid` TINYINT NOT NULL,
-> `empid` TINYINT NOT NULL,
-> `department` CHAR(2)
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `jobs` (
-> `depaermentid`,
-> `empid`,
-> `department`
-> ) VALUES
-> (1, 1, NULL),
-> (1, 2, 'it'),
-> (2, 1, NULL),
-> (2, 2, 'cs');
Query OK, 4 rows affected (0.01 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> SELECT
-> `jobs`.`depaermentid`,
-> `jobs`.`empid`,
-> IFNULL(`jobs`.`department`, `der`.`department`) `department`
-> FROM
-> `jobs`
-> INNER JOIN (
-> SELECT
-> `depaermentid`,
-> `department`
-> FROM
-> `jobs`
-> WHERE
-> `department` IS NOT NULL
-> ) `der` ON `jobs`.`depaermentid` = `der`.`depaermentid`;
+--------------+-------+------------+
| depaermentid | empid | department |
+--------------+-------+------------+
| 1 | 1 | it |
| 1 | 2 | it |
| 2 | 1 | cs |
| 2 | 2 | cs |
+--------------+-------+------------+
4 rows in set (0.00 sec)
请参阅db-fiddle。