简体   繁体   English

SQL LEFT JOIN不返回正确的数据

[英]SQL LEFT JOIN Not returning the correct DATA

Im tryoing to build a SQL join table, but it is not returning the correct data that i want. 我试图建立一个SQL联接表,但它没有返回我想要的正确数据。 So i have a sliders table with structure like below. 所以我有一个具有如下结构的滑块表。 滑块表结构

So the table has a foreign key that referes to an item. 因此,该表具有引用项的外键。 Items or sliders have a same column called: published, that tells if a sliders/items is or is't published. 项目或滑块具有同一列,称为:已发布,用于指示滑块/项目是否已发布。

I'm trying to build a query that returns all sliders that are published AND items where they belonge are published, Joined with the sliders where item_id is nll. 我正在尝试建立一个查询,该查询返回所有已发布的滑块以及它们所属的项目已发布的所有滑块,其中item_id为nll的滑块已加入。

So according to the image above the query should return only 3 rows with id (2-3-4), because item with id 34 (item_id=34) on table items is not published therefore it shouldnt be on the returned value. 因此,根据上面的图片,查询应该仅返回ID为(2-3-4)的3行,因为表项的ID为34(item_id = 34)的项未发布,因此它不应位于返回值上。 The query that i have build so far is this: 到目前为止,我已经建立的查询是:

SELECT *
FROM sliders
LEFT JOIN items ON sliders.item_id = items.id
WHERE sliders.published =1 AND items.published =1

But the query returns only 2 rows. 但是查询仅返回2行。 rows with id 2 and 3 which correspond to item with id 23, 28. ID为2和3的行,分别对应ID为23、28的项。

The returned result is as follow: 返回结果如下:

返回结果

So it returned 2 rows instead of 3, the row missing is the row with id 3, where item_id=null. 因此它返回2行而不是3行,丢失的行是ID为3的行,其中item_id = null。

I have been trying all day to figure this out but it seems i am stuck here... 我整天都在努力解决这个问题,但似乎我被困在这里...

Any help would be very appreciated.. 任何帮助将不胜感激。

If you use a LEFT JOIN and there isn't a match, the right hand table ( items ) will have NULL as the values of its columns. 如果您使用LEFT JOIN而没有匹配项,则右侧表( items )的列值将为NULL You therefore can't have items.published = 1 in your WHERE clause and expect those rows to show up because NULL doesn't equal 1 . 因此,您的WHERE子句中不能包含items.published = 1 ,并且希望显示这些行,因为NULL不等于1

Assuming I've not misunderstood the question, you'll need to change that to AND (items.published IS NULL OR items.published = 1) - you could probably also get away with just doing AND items.published <> 0 . 假设我没有误解这个问题,则需要将其更改为AND (items.published IS NULL OR items.published = 1) -您可能还可以通过执行AND items.published <> 0 That essentially checks that the items are published if they exist . 基本上检查, 如果它们存在的项发布。

This is the Final query that returns the correct Data. 这是返回正确数据的最终查询。

SELECT *
 FROM sliders
  LEFT JOIN items 
    ON sliders.item_id = items.id
WHERE sliders.published =1
 AND (
   items.published IS NULL
   OR items.published =1
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM