简体   繁体   中英

multiple select join union in a single mysqli query

I'm trying to put this left join for three tables in one query.

I can get one select join statement to work at a time, but when I want to get two select statements to work in a query, it doesn't work well.

Basically, I want to get the name of the city and state and not ids.

either city or either state , only one of them would work and give me the name successfully but the other one will only give the id.

I'm trying to get the names for both city and state. How can I accomplish that?

         <?php  
          if($state > 0 && $city  > 0 && $area < 1 ){

       $sqla= "(SELECT listing.*, state.state_name as state FROM listing LEFT JOIN state ON listing.state = state.id) UNION (SELECT listing.*, city.city_name as city FROM listing LEFT JOIN city ON listing.city = city.id)";

          $sql=mysqli_query($con,$sqla);  


            if (mysqli_num_rows($sql) > 0) {
             while($row = mysqli_fetch_array($sql)){ ?>
          <?php echo $row['id']; ?>
       <?php echo $row['state']; ?>
       <?php echo $row['city']; ?>

This is probably because you use UNION statement incorrectly. I guess you wanted to use another left join, this way you have one set of all rows from listing with state_name associated (and city here is city column from listing) and another set of all rows from listing from the second query, again state field is state column from listing table. You should do it like this:

 SELECT listing.*, state.state_name, city.city_name FROM listing LEFT JOIN state ON listing.state = state.id LEFT JOIN city ON listing.city = city.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM