我知道我已经在这里问过这个问题,但没有一个好的答案,所以我再试一次,这一次我希望我能为你们提供足够的信息。
在我提出问题之前,我将向您展示我是如何创建数据库(有用的部分)的:
CREATE TABLE host(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
naam VARCHAR(40) NOT NULL,
isActief BOOLEAN NOT NULL DEFAULT TRUE,
UNIQUE unq_host_naam(naam)
);
CREATE TABLE shows(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
naam VARCHAR(30) NOT NULL,
facebook VARCHAR(50) DEFAULT NULL,
twitter VARCHAR(50) DEFAULT NULL,
isNonStop BOOLEAN NOT NULL DEFAULT FALSE,
showProgrammaInMenu BOOLEAN NOT NULL DEFAULT TRUE,
isActief BOOLEAN NOT NULL DEFAULT TRUE,
UNIQUE unq_shows_naam(naam)
);
/* The following tables (day and hour) were created because MySQL doesn't have CHECK-constraints*/
CREATE TABLE day( id INT NOT NULL PRIMARY KEY );
INSERT INTO day
VALUES (1), (2), (3), (4), (5), (6), (7);
CREATE TABLE hour( id INT NOT NULL PRIMARY KEY );
INSERT INTO hour
VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12), (13), (14), (15), (16), (17), (18), (19), (20), (21), (22), (23);
CREATE TABLE schedule(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
dag INT NOT NULL,
uur INT NOT NULL,
showId INT,
hostId INT,
FOREIGN KEY fk_schedule_day(dag) REFERENCES day(id),
FOREIGN KEY fk_schedule_hour(uur) REFERENCES hour(id),
FOREIGN KEY fk_schedule_shows(showId) REFERENCES shows(id),
FOREIGN KEY fk_schedule_host(hostId) REFERENCES host(id),
UNIQUE unq_schedule_dag_uur(dag, uur)
);
我正在尝试运行此查询:
$query = sprintf("SELECT s.dag, s.uur, h.naam hostName
FROM schedule s, host h
WHERE dag IN (SELECT dag
FROM schedule
WHERE showId = %s)
AND s.hostId = h.id,
AND s.showId = %s
ORDER BY dag, uur",
mysqli_real_escape_string($con, $id),
mysqli_real_escape_string($con, $id));
我知道它不起作用,因为 hostId 可以为 NULL,所以我尝试使用 MySQL 的 IFNULL() 方法来修复它:
SELECT s.dag, s.uur, IFNULL(h.naam, "") hostname
但这没有用。此外,这里提到的选项也不起作用,因为它只会自我中和......
$query = sprintf("SELECT s.dag, s.uur, h.naam hostName
FROM schedule s, host h
WHERE dag IN (SELECT dag
FROM schedule
WHERE showId = %s)
AND (s.hostId = h.id OR ISNULL(s.hostId))
AND s.showId = %s
ORDER BY dag, uur",
mysqli_real_escape_string($con, $id),
mysqli_real_escape_string($con, $id));
这与我在没有
AND (h.id = s.hostId OR ISNULL(s.hostId))