如何在SQL中显示NULL记录

时间:2017-10-18 15:03:39

标签: mysql sql

我有3个表的简单数据库:

Galaxy(GalaxyID INTEGER PRIMARY KEY, Name TEXT);

Planet(PlanetID INTEGER PRIMARY KEY, GalaxyID INTEGER, Name TEXT, Population INTEGER);

Continent(ContinentID INTEGER PRIMARY KEY, PlanetID INTEGER,Name TEXT);

INSERT INTO Galaxy VALUES 
(1, "MILKY WAY"),
(2, "IC 1101"),
(3, "GN-z11");

INSERT INTO Planet VALUES 
(1,1, "Earth", 100000),
(2,1, "Moon", 0),
(3,1, "Saturn", 0),
(4,2, "IC-123", 0),
(5,2, "IC-124", 1),
(6,2, "IC-126", 4),
(7,3, "GN-24", 1),
(8,3, "GN-26", 1),
(9,3, "GN-28", 4);

INSERT INTO Continent VALUES 
(1,1, "Europe"),
(2,4, "UnnamedContinent1"),
(3,4, "UnnamedContinent2");

我想选择一下根本没有大陆的Galaxy:

SELECT Galaxy.Name, Planet.name
FROM Galaxy
LEFT OUTER JOIN Planet, Continent
ON Continent.PlanetID = Planet.PlanetID AND Galaxy.GalaxyID = Planet.GalaxyID
GROUP BY Galaxy.Name
HAVING COUNT(ContinentID) IS NULL

这个查询不会工作,但是如果我给HAVING COUNT(ContinentID)IS NOT NULL,它将覆盖所有Galaxy与大陆(IC 1101和MILKY WAY) 如何显示NULL记录如:GN-z11 NULL

3 个答案:

答案 0 :(得分:1)

不需要COUNT,也不需要having,也不需要group by,只需在continent表中添加额外的左连接:

SELECT DISTINCT g.Name GalaxyName, p.name PlanetName
FROM Galaxy AS g
LEFT JOIN Planet AS p ON g.GalaxyID = p.GalaxyID
LEFT JOIN Continent AS c ON c.PlanetID = p.PlanetID 
WHERE c.PlanetID IS NULL;

Demo

答案 1 :(得分:0)

首先,COUNT()永远不会返回NULL。如果没有匹配的行,则返回0

其次,请勿在{{1​​}}子句中使用逗号。始终使用显式FROM语法。

然后表别名使查询更容易编写和读取。

最后,您只需要一个JOIN子句而不需要聚合:

WHERE

现在,这看起来似乎正在做正确的事情。然而,对于每个没有大陆的行星,都会列出一个星系。快速和肮脏的解决方法是使用SELECT g.Name FROM Galaxy g LEFT JOIN Planet p USING (GalaxyID) LEFT JOIN Continent c USING (PlanetID) WHERE c.PlanetId IS NULL; 而不是SELECT DISTINCT

更好的整体方法是使用SELECT

NOT EXISTS

答案 2 :(得分:0)

我想你可以这样试试:

import {Injectable} from '@angular/core';

@Injectable()
export class PlayerService {
    stream: any;
    promise: any;

    constructor() {
        this.initLiveStream();
    }

    initLiveStream() {
        this.stream = new Audio('http://audio-mp3.ibiblio.org:8000/wcpe.mp3');
    }

    play() {
        this.stream.play();

        this.promise = new Promise((resolve,reject) => {
            this.stream.addEventListener('playing', () => {
                resolve(true);
            });

            this.stream.addEventListener('error', () => {
                reject(false);
            });
        });

        return this.promise;
    };

    pause() {
        this.stream.pause();
    };
}