I have a property database and I am currently designing a query for additional characteristics of the properties. In this case the two tables in question are those:
This is the first Characteristics table which is basically where I store the meta for each characteristic.
This is the CharacteristicsPerProperty database where I store the relation and final value of the specific characteristic.
So basically what I want to do is count all the unique id_propiedad
( property_id
) so that I can show how many I have available with that specific characteristic. The query is the following
SELECT
COUNT(DISTINCT(CaracteristicasPorPropiedad.id_propiedad)) AS disponibles
FROM
CaracteristicasPorPropiedad
WHERE
CaracteristicasPorPropiedad.id_caracteristica = 1
AND
CaracteristicasPorPropiedad.valor = 3
So basically the output is something like:
| disponibles |
|=============|
| 264 |
Everything works as expected up to here, but I can also include another parameter, let's say in the previous example I included Recámaras (Bedrooms), but I also want to include Baños (Bathrooms). I tried
SELECT
COUNT(DISTINCT(CaracteristicasPorPropiedad.id_propiedad))
FROM
CaracteristicasPorPropiedad
WHERE
(CaracteristicasPorPropiedad.id_caracteristica = 1 AND CaracteristicasPorPropiedad.valor = 3)
AND
(CaracteristicasPorPropiedad.id_caracteristica = 2 AND CaracteristicasPorPropiedad.valor = 2.5)
The thing is that this query returns 0.
If I switch the AND to an OR it returns 282 results. I basically need the combination of both. I am a little stuck with this. What could be a query to mix multiple levels of this? It can be used with all 10 available dimensions for this characteristic.
You can get the id_propiedad
using aggregation:
SELECT cpd.id_propiedad
FROM CaracteristicasPorPropiedad cpd
WHERE (cpd.id_caracteristica = 1 AND cpd.valor = 3) OR
(cpd.id_caracteristica = 2 AND cpd.valor = 2.5)
GROUP BY cpd.id_propiedad
HAVING COUNT(DISTINCT cpd.id_caracteristica) = 2;
If you want the count, use a subquery:
SELECT COUNT(*)
FROM (SELECT cpd.id_propiedad
FROM CaracteristicasPorPropiedad cpd
WHERE (cpd.id_caracteristica = 1 AND cpd.valor = 3) OR
(cpd.id_caracteristica = 2 AND cpd.valor = 2.5)
GROUP BY cpd.id_propiedad
HAVING COUNT(DISTINCT cpd.id_caracteristica) = 2
) p;
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.