如果没有在T2中替换,则mysql从T1中选择

时间:2016-06-28 19:53:55

标签: php mysql sql

所以我试图写的mysql PDO查询必须比较来自两个表和输出数组的列。

  1. 如果来自table1的空输出数据
  2. 如果单元格的值与table2相同,     输出该值作为第一个,然后输出所有其他值。
  3. 工作表:

    table1
    |jobName|Name|
    |job1   |John|
    |job2   |John|
    |job3   |John|
    |jobABC |Jack|
    |jobCCC |Jack|
    |jobXYZ |Jack|
    

    和日表:

    table2
    |day |jobName|Name|
    |day1|       |John|
    |day1|jobCCC |Jack|
    |day2|job2   |John|
    |day2|       |Jack|
    |day3|jobXYZ |Jack|
    |day3|job1   |John|
    

    并且John的输出应为:

    day1, job1, job2, job3
    day2, job2, job1, job3
    day3, job1, job2, job3
    

    杰克的输出应为:

    day1, jobCCC, jobABC, jobXYZ
    day2, jobABC, jobCCC, jobXYZ
    day3, jobXYZ, jobABC, jobCCC
    

    谢谢!

1 个答案:

答案 0 :(得分:1)

我接近了......有人在乎帮助我吗?

http://sqlfiddle.com/#!9/e5a510/12

SELECT 
  b.Day,
  COALESCE(a.Name, b.Name) AS Name, 
  COALESCE(a.JobName, b.JobName) AS JobName
FROM table1 a, table2 b
WHERE a.Name = b.Name

更新!

这是最终产品(我认为):

http://sqlfiddle.com/#!9/e5a510/53

SELECT 
  b.Day,
  COALESCE(a.Name, b.Name) AS Name, 
  COALESCE(a.JobName, b.JobName) AS JobName
FROM table1 a, table2 b
WHERE a.Name = b.Name AND a.Name = 'Jack' 
ORDER BY   b.Day ASC, a.JobName = b.JobName DESC, a.JobName ASC