简体   繁体   中英

SQL Query Assistance - Left join unexpected result

I have these 2 queries:

$sql = "SELECT *
FROM ultrait_wpl_properties
LEFT JOIN ultrait_wpl_property_types
ON ultrait_wpl_properties.property_type = ultrait_wpl_property_types.id
ORDER BY ultrait_wpl_properties.id  ";

$sql2 = "SELECT * 
FROM ultrait_wpl_properties, ultrait_wpl_property_types
WHERE  ultrait_wpl_properties.property_type = ultrait_wpl_property_types.id
ORDER BY ultrait_wpl_properties.id";

For some odd reason when the IDs are output some are duplicated? By my reseaning these queries should get everything from the table in the first part and join the second table based on the WHERE condition.

<property><id>13</id></property>
<property><id>6</id></property>
<property><id>6</id></property>
<property><id>6</id></property>
<property><id>6</id></property>
<property><id>7</id></property>

This may be slightly unclear but for some reason I'm getting duplicate IDs, all i want really is to be able to access the property type which links to the ID in the second table.

I have tested both queries in phpMyAdmin and they yeild the desired result, however when I use the queries in my php script they return unexpected results.

You are getting a Cartesian result in the case the ultrait_wpl_property_types table has multiple records for a single property. Such as a property type could be Type A, Type B, Type C which might be descriptive "types". So a single property would be accounted for each entry.

You might just need to do SELECT DISTINCT, or GROUP BY ultrait_wpl_properties.id to make sure only one record per ID, but with generic "Select * ", I would first try with GROUP BY.

You are getting one row for each row in table ultrait_wpl_properties. What else do you expect? If it is just one record per type, then you would have to re-write your query accordingly. You select * from both tables. But is it only the type ID you need? Then why join the tables at all?

Get all type IDs:

select id from ultrait_wpl_property_types;

Get all type IDs in table ultrait_wpl_properties:

select distinct property_type from ultrait_wpl_properties;

Get all type data for types in ultrait_wpl_properties:

select * from ultrait_wpl_property_types
where id in (select property_type from ultrait_wpl_properties);

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