【问题标题】:Why is my result empty when using this query为什么使用此查询时我的结果为空
【发布时间】:2018-04-07 10:39:23
【问题描述】:

我正在获取产品以及该产品所属的类别以显示在页面上。我还得到了一些属于不同表中产品的数据。

我的查询如下所示:

SELECT cnt.id as content_id, cnt.title as content_title, cnt.featured, cnt.alias as content_alias, cnt.catid, cnt.images, cnt.state, cnt.introtext, cat.id as cat_id, cat.title as cat_title, cat.alias as cat_alias,
MAX(case when f.field_id = 4 then f.value end) as prijs,
MAX(case when f.field_id = 5 then f.value end) as prijsoud
FROM snm_fields_values f
JOIN snm_content cnt
ON cnt.id = f.item_id
JOIN snm_categories cat
ON cnt.catid = cat.id
WHERE cnt.catid = '17'
AND cnt.state = 1
GROUP BY f.item_id

我的问题是,当一个类别下没有任何文章时,所有结果都是空的。因此,在没有属于该类别的产品的类别页面上,它也不会显示类别标题。

只有当类别下有产品(snm_content)时,才会显示所有数据。

以上查询返回以下内容:

catid 17 下没有产品。

当我将其更改为 16(确实有产品)时,这是我的结果:

我想获取那里的所有数据,所以当一个类别没有产品时,我仍然需要类别标题。

当一个产品不存在时,为什么一切都是空的?

【问题讨论】:

  • 看看左右连接。当子表中不存在行时,它们将包含父表中的行。
  • 您使用了 equi join (w3resource.com/sql/joins/perform-an-equi-join.php),它基本上返回满足您在 where 子句中提到的相同条件的数据。因此,您需要使用 LEFT OUTER JOIN 或 RIGHT OUTER JOIN 来返回非 equi 数据。请查看(w3schools.com/sql/sql_join_left.asp)
  • @SloanThrasher 我尝试使用这两种方法,但无论如何我都会得到一个空的结果。我已经尝试了 LEFT/RIGHT JOIN 和 LEFT OUTER/RIGHT OUTER JOIN 但没有结果。
  • 正确使用GROUP BY。它甚至不是一个有效的GROUP BY。所有这些非聚合列都需要在GROUP BY 子句中。

标签: mysql sql database


【解决方案1】:

我认为你想要外部连接。我不完全理解GROUP BY,但这可能会满足你的要求:

SELECT cnt.id as content_id, cnt.title as content_title, cnt.featured, cnt.alias as content_alias, cnt.catid, cnt.images, cnt.state, cnt.introtext, cat.id as cat_id, cat.title as cat_title, cat.alias as cat_alias,
       MAX(case when f.field_id = 4 then f.value end) as prijs,
       MAX(case when f.field_id = 5 then f.value end) as prijsoud
FROM snm_categories cat LEFT JOIN
     snm_content cnt
     ON cnt.catid = cat.id AND cnt.state = 1 LEFT JOIN
     snm_fields_values f 
     ON cnt.id = f.item_id 
WHERE cat.id = 17
GROUP BY cnt.id, cnt.title, cnt.featured, cnt.alias, cnt.catid, cnt.images, cnt.state, cnt.introtext, cat.id, cat.title, cat.alias

【讨论】:

  • cat.catid 需要是 cnt.catid 但是当我使用它时,我仍然得到一个空的结果。
  • @twan 。 . .应该是cat.id
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-04
  • 1970-01-01
  • 2022-10-25
  • 1970-01-01
  • 2019-10-27
相关资源
最近更新 更多