简体   繁体   中英

MySQL JOIN on different column names

I have two tables with similar data but entirely different column names. I make the query in a PHP page and then use the data in echo statements like this:

<?php echo($row['bedrooms']); ?>

The current query looks like this:

$sql_query = "SELECT mls_number, city, list_price, bedrooms 
                  FROM bonita_property_res 
                  WHERE city = "Bonita" AND list_price >= 1500000 
                  ORDER BY list_price DESC";

How do a join a table called naples_property_res that looks like this and still be able to use the php echo as its configured?

MLSNumber     City       ListPrice      TotalBeds
--------------------------------------------------
898989   | Bonita    | 200000     |  4

It doesn't sound like you want to use a JOIN , but rather a UNION

SELECT fields FROM bonita_property_res WHERE conditions
UNION SELECT fields FROM naples_property_res WHERE conditions

Use UNION:

SELECT mls_number, city, list_price, bedrooms FROM bonita_property_res WHERE ...
UNION 
SELECT MLSNumber AS mls_number, City AS city, ListPrice AS list_price, TotalBeds AS bedrooms FROM naples_property_res WHERE ...

The column aliases - something AS something_else - ensure that you don't break any references in PHP, eg $row['bedrooms'].

Well you didn't tell us what the "entirely different column names" are but it would look something like this:

SELECT mls_number, city, list_price, bedrooms 
FROM bonita_property_res 
WHERE city = "Bonita" AND list_price >= 1500000 
ORDER BY list_price DESC
UNION
SELECT entirely, different, column, names
FROM naples_property_res
WHERE ......

You can just use ALIAS to the columns.

$sql_query = "SELECT colA AS mls_number, colB AS city, colC AS list_price, 
                  colD AS bedrooms FROM naples_property_res WHERE ...";

And make a UNION .

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