两个查询,两个不同的表,只有一个循环

时间:2013-12-11 22:11:37

标签: php mysql sql

我想为两个不同的表运行两个select语句,但是将它们列在一个循环中。目前我独立运行它们,但这并不理想,因为我希望整个日期顺序中列出的记录。列名和列号不同。

简化当前设置

     $SQL = "SELECT * FROM table1 WHERE colA IS NOT NULL ORDER BY dateA";
     $DataOne = mysql_query($SQL);

     $SQL = "SELECT * FROM table2 WHERE colZ IS NOT NULL ORDER BY dateZ";
     $DataTwo = mysql_query($SQL);

     while ($row = mysql_fetch_assoc($DataOne)) {
         echo "<td>$row[colA]</td>"; 
     } 

        while ($row = mysql_fetch_assoc($DataTwo)) {
         echo "<td>$row[colZ]</td>"; 
     }

所需的设置(逻辑上)

while ($row = mysql_fetch_assoc($DataOne, $DataTwo)) {
    // all returned rows from both tables in date order
    echo "<td>$row[EitherCol]</td>";
}

信息:我知道我应该使用mysqlipdo但目前不是一个选项

3 个答案:

答案 0 :(得分:2)

如果列数及其类型相同,请使用UNION运算符。列名将从第一个查询中获取,以防它们不同。

不是最后一个,请避免使用“SELECT *”并改为枚举列。

在你的情况下,我会这样做:

SELECT colA as EitherCol FROM table1 WHERE colA IS NOT NULL ORDER BY dateA
UNION
SELECT colZ as EitherCol FROM table2 WHERE colZ IS NOT NULL ORDER BY dateZ

答案 1 :(得分:1)

使用UNION ......就像这样。

$SQL = "(SELECT * FROM table1 WHERE colA IS NOT NULL) UNION (SELECT * FROM table2 WHERE colZ IS NOT NULL) ORDER BY date";

$Data = mysql_query($SQL);

while ($row = mysql_fetch_assoc($Data)) {
// all returned rows from both tables in date order
echo "<td>$row[EitherCol]</td>";
}

答案 2 :(得分:0)

仅选择相关列并将它们命名为相同

即。

SELECT colA1 as col1 , colA2 as col2 , colA3 as col3 , dateA as date FROM table1
UNION
SELECT colB1 as col1 , colB2 as col2 , '' as col3 , dateB as date FROM table2
ORDER BY date

如果你看一下col3这是你可以做的一个例子,如果你绝对需要来自table1的东西而且它在表2中不存在

最后,使日期别名可让您按日期订购最终表格