MySQL:如果存在则从其他表中选择,否则从当前表中选择

时间:2017-04-27 00:58:11

标签: php mysql

你能帮我构建一个SQL查询来获取2表中的数据列表,如果第二个表中存在数据,它应该显示来自它的数据,否则来自table1

表1:

ID | NAME    | AGE 
------------------
1  | John    | 20
2  | Daniel  | 30
3  | Abraham | 30
4  | Donald  | 25

表2:

ID | NAME    | AGE 
------------------
1  | John    | 23
2  | Donald  | 24

期望的结果:约翰和唐纳德" 年龄"从表2中获取数据,其余来自表1

ID | NAME    | AGE 
------------------
1  | John    | 23
2  | Daniel  | 30
3  | Abraham | 30
4  | Donald  | 24

请参阅http://www.sqlfiddle.com/#!9/9539b0

2 个答案:

答案 0 :(得分:2)

使用自动增量ID加入的表

SELECT t1.id, t1.name, IF(t2.id, t2.age, t1.age) AS age
FROM Clients AS t1
LEFT JOIN Records AS t2 ON (t1.id = t2.id)

或使用名称

加入的表格
SELECT t1.id, t1.name, IF(t2.name, t2.age, t1.age) AS age
FROM Clients AS t1
LEFT JOIN Records AS t2 ON (t1.name = t2.name)

答案 1 :(得分:1)

记录的外部联接,并测试age的NULL值。像这样:

SELECT c.id
     , c.name
     , IFNULL(r.age,c.age) AS age
  FROM Clients c
  LEFT
  JOIN Records r
    ON r.name = c.name
 ORDER BY c.id

http://www.sqlfiddle.com/#!9/9539b0/4