gpt4 book ai didi

mysql - SQL 查询、有效日期和连接 : how to make it work?

转载 作者:行者123 更新时间:2023-11-29 00:46:38 24 4
gpt4 key购买 nike

以下所有 3 个表格都有一个“date_v_end”字段,这是一个有效日期。只要它是 NULL,就意味着它是当前的“好”值。

例如,要选择表 categorie 的当前值,我们可以简单地执行 SELECT * FROM categorie WHERE date_v_end IS NULL

我有 3 个表:

  • 一个表categorie(英文类别)
  • “一对多”表categorie_produit(英文类别<=>产品)
  • 一个表格produit(英文产品)

我想查询所有当前 类别,以及它们的一对多产品,我仍然需要一个结果 即使该类别没有产品(= 没有 produit_categorie 行)。

在使用“date_v_end”字段之前,我是这样做的:

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;

它就像一个魅力。现在我正在尝试使用新的“date_v_end”字段修改查询。我添加了三个子句 WHERE c.date_v_fin IS NULL AND cp.date_v_fin IS NULL AND p.date_v_fin IS NULL。给你:

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;

除了在一种情况下,这工作正常:当有一个 categorie_produit 并且它的“date_v_end不是 NULL:在添加这个该死的“date_v_end”字段之前,我得到了一个行,其中填充了 c_id、c_titre 和 c_description 以及其他字段 NULL (cp_id_categorie, cp_id_produit, p_id, p_titre, p_description).现在没有结果。

我真的不知道如何修改我的查询以使其工作。有什么想法吗?

最佳答案

您需要将 IS NULL 检查移动到 JOIN 中。

在你加入的版本中,不管date_v_fin字段,然后过滤结果。

在下面的查询中,仅当 date_v_fin 字段为 NULL 时才加入记录。

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 c
LEFT OUTER JOIN
categorie_produit cp
ON c.id=cp.id_categorie
AND cp.date_v_fin IS NULL
LEFT OUTER JOIN
produit p
ON p.id=cp.id_produit
AND p.date_v_fin IS NULL
WHERE
c.date_v_fin IS NULL
ORDER BY
c_id,
p_id

关于mysql - SQL 查询、有效日期和连接 : how to make it work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10283453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com