Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Sep 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Problem with joining 2 mysql queries and displaying them using php

    Hi All,

    Below is my code to add the two different query results into one. This is working fine when both the queries have same no.of rows.

    eg: row1 = 1 2 3 (Query1)

    row2 = 3 5 5 (Query2)

    o/p: 4 7 8

    Let's say, I have few rows which are not exactly matched with first query.

    eg: row1 = 1 2 3 2 (Query1)

    row2 = 3 empty empty 5 (Query2)

    o/p : 4 2 3 7 (I want the o/p to be like this)

    empty means there is no data from the second query.

    In my while, && working fine when the 2 queries have same no.of rows.


    while (($row1 = mysql_fetch_assoc($rs1)) && ($row2 = mysql_fetch_assoc($rs2)))
    {


    $strHtml .= "<tr>";

    $strHtml .= "<td align=center colspan=3>".($row1['Calls']+$row2['Calls'])."</td>";
    $strHtml .= "<td align=center colspan=3>".($row1['actual_duration(min)A']+$row2['actual_duration(min)A'])."</td>";
    $strHtml .= "<td align=center colspan=3>".($row1['call_usage']+$row2['call_usage'])."</td>";
    $strHtml .= "<td align=center colspan=3>".($row1['disconnection_charge']+$row2['disconnection_charge'])."</td>";
    $strHtml .= "<td align=center colspan=3>".($row1['total_revenue']+$row2['total_revenue'])."</td>";

    $strHtml .= "</tr>";

    }

    Is the while loop i am using correct or there is any other better solution for this?

    please help me, Thanks in advance.

  • #2
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,500
    Thanks
    8
    Thanked 1,089 Times in 1,080 Posts
    How about using UNION?

    http://www.plus2net.com/sql_tutorial/sql_union.php

    Give us the names of your tables, and the column names.
    Maybe we can make an example for you.

    NOTE:
    An alternative is JOIN, but without knowing your column names,
    I can't say whether or not that would be better to use.
    http://www.plus2net.com/sql_tutorial/sql_left_join.php

    The difference between JOIN and UNION (from the Tizag tutorial):
    SQL UNION combines two separate SQL queries into one result set. A JOIN statement adds additional table columns to a result set (horizontally), UNION combines row results from one table with rows of another table (vertically).


    .
    Last edited by mlseim; 09-12-2011 at 01:22 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •