All the 3 following tables have a “date_v_end” field which is a validity date. As long as it’s NULL this means it’s the current “good” value.
For example, to select the current values of the table categorie we can simply do SELECT * FROM categorie WHERE date_v_end IS NULL.
I have 3 tables:
- a table
categorie(category in English) - a table “one to many”
categorie_produit(category <=> product in English) - a table
produit(product in English)
I’d like to make a query of all the current categories, and their one to many produit, and I still need one result even if the category has no product (= no produit_categorie row).
Before having the “date_v_end” field I did it this way:
SELECT
c.id AS c_id,
c.titre AS c_titre,
c.description AS c_description,
cp.id_categorie AS cp_id_categorie,
cp.id_produit AS cp_id_produit,
p.id AS p_id,
p.titre AS p_titre,
p.description AS p_description
FROM categorie_produit cp
LEFT OUTER JOIN categorie c
ON c.id=cp.id_categorie
LEFT OUTER JOIN produit p
ON p.id=cp.id_produit
ORDER BY c_id,p_id;
It worked like a charm. Now I’m trying to modify the query with the new “date_v_end” field. I’ve added the three clauses WHERE c.date_v_fin IS NULL AND cp.date_v_fin IS NULL AND p.date_v_fin IS NULL. There you go:
SELECT
c.id AS c_id,
c.titre AS c_titre,
c.description AS c_description,
cp.id_categorie AS cp_id_categorie,
cp.id_produit AS cp_id_produit,
p.id AS p_id,
p.titre AS p_titre,
p.description AS p_description
FROM categorie_produit cp
LEFT OUTER JOIN categorie c
ON (c.id=cp.id_categorie AND c.date_v_fin IS NULL)
LEFT OUTER JOIN produit p
ON (p.id=cp.id_produit AND p.date_v_fin IS NULL)
WHERE cp.date_v_fin IS NULL
ORDER BY c_id,p_id;
This works fine except in one circumstance: when there’s a categorie_produit and its “date_v_end” is not NULL: before adding this damn “date_v_end” field, I got one row with c_id, c_titre, and c_description filled and the other fields NULL (cp_id_categorie, cp_id_produit,p_id,p_titre,p_description). Now there’s no result.
I really don’t know how I can modify my query to make it work. Any idea?
You need to move the
IS NULLcheck into the JOINs.In your version you join, regardless of the
date_v_finfield, and then filter the results.In the query below a record is only joined if the date_v_fin field IS NULL.