我有两张桌子
第一个:
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
...
我该怎么做?也许有一个联盟?非常感谢你!
最佳答案
在我看来,这里的最佳实践是在第一张表中添加另一列,该列是与第一张表的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]." ".$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]." ".$row[1]."</p>";
$countInner++;
}
}
}
这应该给您一些一般性的想法,我没有时间去测试它,但是它应该为您指明一般的方向。
关于mysql - MySQL正确的SELECT语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38534168/