MySql正确的SELECT语句

时间:2016-07-22 19:41:34

标签: mysql

我有两张桌子,

第一个:

things                descriptions
------                ------------
First thing           First description
Second thing          Second description
Third thing           Third description
Fourth thing          Fourth description

...

第二个:

id       products
--       --------
1        First product
2        Second product
3        Third product
4        Fourth product

...

我需要一个查询来显示第一个表中的前两行,然后显示第二个表的第一行,然后是第一个表中的第二行,然后是第二个表的第二行,依此类推,获取这样:

things+id            prod+descr
---------            ----------
First thing          First description
Second thing         Second description
1                    First product
Third thing          Third description
Fourth thing         Fourth description
2                    Second product

...

我该怎么办?也许与UNION?非常感谢你!

1 个答案:

答案 0 :(得分:0)

在我看来,最好的做法就是在第一个表中添加另一列,这是与第一个表的PK匹配的FK。拥有这样的数据是否可以接受?然后在程序中检索它?

t2.ID  t2.prod     t1.thing      t1.desc
------ -------     --------      -------------
1      first prod  first thing   first desc
1      first prod  second thing  second desc

更新:根据您的需求

 // setup count 
 $countOuter = 0;
 $countInner = 0;

 //connect
 $mysqli = mysqli_connect(localhost,user,pass,database);

 // heres the tricky part you will have to make sure that your 
 // tables are filled out at a ratio of 2:1  or there could be an 
 // error thrown 

 // not sure if this is going to be necessary for your purposes
 $sqlTest = "select * from tableOne"
 $sqlTest2 = "select * from tableTwo"     
 $result1 = mysqli_query($mysqli, $sqlTest) or die (mysqli_error($mysqli));
 $result2 = mysqli_query($mysqli, $sqlTest2) or die (mysqli_error($mysqli));
 $rowsTableOne = mysqli_num_rows($result1);
 $rowsTableTwo = mysqli_num_rows($result2);

 // check ratio 
 if(($rowsTableOne / $rowsTableTwo) == 2) 
{

     while($countOuter < $rowsTableOne)
     {
      //outer query 
      $sqlOuter = "select * from tableOne LIMIT 2";
      if ($count % 2 == 0) {
       $sqlOuter .= " OFFSET ".$count;
      }
       $result = mysqli_query($mysqli, $sqlOuter) or die (mysqli_error($mysqli));    
      while($row = mysqli_fetch_array($result, MYSQLI_NUM))
      {        
          echo "<p>".$row[0]."&nbsp;".$row[1]."</p>";
          $countOuter++;
      }

      $sqlInner = "select * from tableTwo LIMIT 1";
      if ($countInner != 1) {
       $sqlInner .= " OFFSET ".$countInner;
      }
      $result = mysqli_query($mysqli, $sqlInner) or die (mysqli_error($mysqli));    
      while($row = mysqli_fetch_array($result, MYSQLI_NUM))
      {        
          echo "<p>".$row[0]."&nbsp;".$row[1]."</p>";
          $countInner++;
      }
     }
}

这应该给你一些一般的想法,我没有时间测试它,但它应该指向你的大方向。