Sql Join查询的行结果

时间:2013-02-09 08:53:48

标签: mysql select join

请帮助解决以下问题

我有一张桌子:人

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

我有一个query1

(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 

我有一个query2

(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

1 个答案:

答案 0 :(得分: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

点击Here进行演示

以下是您的查询,稍作修改

(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在union的第二部分的name1中。 如果Name1字段为空,则此查询从表IFNULL检查中获取结果。如果这是空的,则执行IFNULL的第二个参数,它是一个子查询并将获取一个名称。如果您需要更多帮助,请在谷歌上做一些研究。