简体   繁体   English

我如何使用mysql中的单个查询从两个表中获取数据

[英]How do i get data from two tables using single query in mysql

I have two tables, with the following columns: 我有两个表,其中包含以下各列:

  • OneRecord : team1 , team2 , id OneRecordteam1team2id
  • fixture_list : team1 , team2 , photo1 , photo2 fixture_listteam1team2photo1photo2

I want to retrieve photo1 , photo2 from fixture_list , if team1 and team2 have the same value on both tables. 我想取回photo1photo2fixture_list如果 team1team2有两个表上相同的值。

This is what I have tried so far: 到目前为止,这是我尝试过的:

<?php
 //checking if the script received a post request or not 
 if($_SERVER['REQUEST_METHOD']=='POST'){
     //Getting post data 
     $email=$_POST['email'];
     require_once('connect.php');
     $sql = "SELECT * FROM OneRecord, fixture_list
             WHERE OneRecord.email='$email', 
                   OneRecord.team1=fixture_list.team1_name 
             AND 
                   OneRecord.team2=fixture_list.team2_name";

     $res = mysqli_query($con,$sql);
     $result = array();

     while($row = mysqli_fetch_array($res)){
         array_push($result, array(
            'team1'=>$row[3],
            'team2'=>$row[4],
            'rs'=>$row[6],
            'team1_score'=>$row[7],
            'team1_wicket'=>$row[8],
            'team2_score'=>$row[10],
            'team2_wicket'=>$row[11],
            'tournament'=>$row[13]
         ));
     }
     echo json_encode (array("bets_list"=>$result));
     mysqli_close($con);

  }

 ?>

this is edited question 这是编辑过的问题

<?php
  //checking if the script received a post request or not 
  if($_SERVER['REQUEST_METHOD']=='POST'){

  //Getting post data 
   $email=$_POST['email'];

 require_once('connect.php'); 
 $sql = "SELECT f.team1_photo as "team1_photo",
 f.team2_photo as "team2_photo" FROM OneRecord o INNER JOIN fixture_list f 
 ON 
 o.team1=f.team1_name AND o.team2=f.team2_name WHERE o.email='$email'";

 $res = mysqli_query($con,$sql);
 $result = array();

 while($row = mysqli_fetch_array($res)){
  array_push($result,
  array('team1'=>$row[3],'team2'=>$row[4],
 'rs'=>$row[6],'team1_score'=>$row[7],'team1_wicket'=>$row[8],
 'team2_score'=>$row[10],
 'team2_wicket'=>$row[11],'tournament'=>$row[13],'photo1'=>$row[0],
 'photo2'=>$row[1],
  ));
    }
   echo json_encode (array("bets_list"=>$result));
  mysqli_close($con);

   }

   ?>

Do an inner join of these 2 tables on team1 and team2 . 做一个内部联接这2个表team1team2

SELECT f.photo1 as "photo1",f.photo2 as "photo2", 
FROM OneRecord o 
INNER JOIN fixture_list f
ON o.team1 = f.team1 and o.team2 = f.team2
where o.email = $email;

UPDATE - If you want all columns, do select * from ... . 更新 -如果需要所有列,请select * from ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM