如何从表中连接2行?

时间:2017-07-27 07:45:25

标签: mysql sql

您好我在这里有一个表格,其中包含以下栏目:ApplicantIDNameAge。我想知道如何加入2行申请人一起显示在同一个表(PHP)上。我试图从数据库中检索它。谢谢!

--------------------------------------
Applicant ID       Name       Age
--------------------------------------
001                John       20
002                Nick       22

以下是我希望它返回的内容

--------------------------------------
Name1       Age1     Name2    Age2
--------------------------------------
John         20      Nick     22

编辑:Amit的代码工作,但返回的数据是:

Name1       Age1     Name2    Age2
--------------------------------------
John         20      Nick     22
--------------------------------------
Nick         22      Judy     25

我如何只返回一次尼克?

3 个答案:

答案 0 :(得分:2)

如果你使用的是php,它可能是这样的:

让我们假设我们有一个与你的表具有相同值的数组。

$arr = [ 
          ['Applicant ID' => 001, 'Name' => 'John', 'Age' => 20],
          ['Applicant ID' => 002, 'Name' => 'Nick', 'Age' => 22],
       ];

$res = [];

foreach($arr as $key => $values){
   $names = 'Name'.($key+1);
   $ages = 'Age'.($key+1);
   $res[$names] = $values['Name'];
   $res[$ages]  = $values['Age'];
}

答案 1 :(得分:1)

您可以使用跨行(自我)联接过滤行

  select a.name as name1, a.age as age1, b.name as name2, b.age as age2
  from  table1 as a
  cross join table2 as b 
  where a.applicant_ID = '001'
  and b.applicant_ID ='002'

答案 2 :(得分:0)

您可以使用以下查询来使用自联接: -

SELECT applicant1.name, 
       applicant1.age,
       applicant2.name, 
       applicant2.age 
FROM applicant as applicant1
JOIN applicant applicant2 
    on applicant1.applicant_id+1 = applicant2.applicant_id;