1

请帮助解决以下问题

我有一张桌子:人

Id   Leader Name1   Name2   StartDate  EndDate
123  1      Person1         2013-02-11 2013-02-17
123  0              Person2 2013-02-13 2013-02-13
123  0              Person3 2013-02-13 2013-02-13

我有一个问题1

(SELECT t1.Id, t1.Name1, t1.Name2
FROM `dbo`.`people` t1
WHERE t1.StartDate >= '2013-02-11'
AND t1.Leader = 1)

UNION 

(SELECT t2.Id, t2.Name1, t1.Name2
FROM `dbo`.`people` t2
WHERE t2.StartDate >= '2013-02-11'
AND t2.Leader = 0)

这返回

Id   Name1   Name2
123, Person1 

我有一个查询2

(SELECT t1.Id, t1.Name1, t1.Name2
FROM `dbo`.`people` t1
WHERE t1.StartDate >= '2013-02-13'
AND t1.Leader = 1)

UNION 

(SELECT t2.Id, t2.Name1, t1.Name2
FROM `dbo`.`people` t2
WHERE t2.StartDate >= '2013-02-13'
AND t2.Leader = 0)

这返回

Id   Name1   Name2
123, Person1 
123,         Person2
123,         Person3

我需要 2012-02-11 的结果来显示

Id   Name1   Name2
123, Person1 null

并为 2012-02-13 显示

Id   Name1   Name2
123, Person1 Person2
123, Person1 Person3
4

1 回答 1

1

这是一个满足您期望结果的查询

(SELECT 
  id,
  name1,
  IFNULL(name2, 'No one available') AS name2,
  startdate AS `date` 
FROM
  person 
WHERE startdate = '2013-02-11') 
UNION
ALL 
(SELECT 
  p.id,
  IFNULL(p.name1, pl.name1) AS name1,
  IFNULL(p.name2, 'Noone available') AS name2,
  p.startdate AS `DATE` 
FROM
  person AS p 
  LEFT JOIN person AS pl 
    ON pl.leader = p.id 
WHERE p.startdate = '2013-02-13')

输出

id  name1       name2               date
---------------------------------------------------
1   Person1     No one available    2013-02-11
1   Person1     Person2             2013-02-13
1   Person1     Person3             2013-02-13

点击这里进行演示

这是您的查询,稍作修改

(SELECT 
  t1.Id,
  t1.Name1,
  IFNULL(t1.Name2, 'Null') AS Name2 
FROM
  `dbo`.`people` t1 
WHERE t1.StartDate >= '2013-02-13' 
  AND t1.Leader = 1) 
UNION
(SELECT 
  t2.Id,
  IFNULL(t2.Name1, p.leader) AS Name1,
  t1.Name2 
FROM
  `dbo`.`people` t2 
  LEFT JOIN people AS p 
    ON p.leader = t2.id 
WHERE t2.StartDate >= '2013-02-13' 
  AND t2.Leader = 0)

编辑

另一种选择是使用子查询

(SELECT 
  t1.Id,
  t1.Name1,
  IFNULL(t1.Name2, 'Null') AS Name2 
FROM
  `dbo`.`people` t1 
WHERE t1.StartDate >= '2013-02-13' 
  AND t1.Leader = 1) 
UNION
(SELECT 
  t2.Id,
  IFNULL(t2.Name1, (SELECT name1 FROM people WHERE t2.StartDate = '2013-02-13')) AS Name1,
  t2.Name2 
FROM
  `dbo`.`people` t2 
WHERE t2.StartDate >= '2013-02-13' 
  AND t2.Leader = 0)

删除连接并使用子查询,同时在联合的第二部分中选择 ifnull 进入 name1。此查询从表 IFNULL 中获取结果,检查 Name1 字段是否为空。如果这是空的,则执行 IFNULL 的第二个参数,它是一个子查询并将获取一个名称。如果您需要更多帮助,请在 google 上进行一些研究。

于 2013-02-09T09:21:11.743 回答