Matching data from 3 tables

Discussion in 'Databases' started by hmilesjr, Apr 25, 2009.

  1. #1
    I have a real estate site that I need some code help on. There are 3 database tables and I want to pull only the information from the tbl_user that matches criteria from the other 2 tables. I tried this but it doesn't seem to be working.

    <?
    $stateswhere="";
    if($stateid<>"")
    {
    $stateswhere=" and tbl_state.stateid='$stateid' ";
    }

    $rs= mysql_query("select * from tbl_users left outer join tbl_state and tbl_property on tbl_state.statename=tbl_users.state and tbl_users.user_id=tbl_property.p_user_id where tbl_users.user_featured=1 and tbl_users.user_isadmin=0 and tbl_users.user_isactive=1 and tbl_property.p_show_sites like '%,1,%' $stateswhere order by rand() limit 0,1");

    if(mysql_num_rows($rs)>0)
    {
    while($row=mysql_fetch_array($rs))
    {?>

    Any help would be appreciated. Will provide positive iTrader
     
    hmilesjr, Apr 25, 2009 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    Try this for the query:

    SELECT * FROM tbl_users LEFT JOIN tbl_state ON tbl_users.state = tbl_state.statename
    LEFT JOIN tbl_property ON tbl_users.user_id = tbl_property.p_user_id
    WHERE tbl_users.user_featured = 1
    AND tbl_users.user_isadmin = 0
    AND tbl_users.user_isactive=1
    AND tbl_property.p_show_sites LIKE '%,1,%'
    $stateswhere
    ORDER BY rand() LIMIT 0,1
     
    jestep, Apr 27, 2009 IP