简体   繁体   English

左联接可选表

[英]left join optional table

i try to select table pep_posts then left join with pep_postmeta but table pep_postmeta is optional mean if no data in table pep_postmeta , the result still can show. 我尝试选择表pep_posts然后与pep_postmeta左连接,但是表pep_postmeta是可选的,意味着如果表pep_postmeta没有数据,结果仍然可以显示。

below is my query but this query only show data if table pep_postmeta has data, this not what i want. 下面是我的查询,但此查询仅在表pep_postmeta有数据的情况下显示数据,这不是我想要的。

select p.*, pm.* 
from `pep_posts` p 
left join `pep_postmeta` pm 
  on pm.post_id=p.ID 
where p.post_parent='".$current_page_id."' and
     p.post_status='publish' and pm.meta_key='book_image' 

In a left join, if you reference the optional table in the WHERE clause, it will still filter out only the rows that have a value in that table. 在左联接中,如果您在WHERE子句中引用了可选表,它将仍然仅过滤出该表中具有值的行。 What you need to do is move the condition on pm to the ON clause where it won't remove rows, just set the values to NULL . 您需要做的是将pm上的条件移动到ON子句,该子句不会删除行,只需将值设置为NULL

SELECT p.*, pm.* 
FROM `pep_posts` p 
LEFT JOIN `pep_postmeta` pm 
  ON pm.post_id=p.ID and pm.meta_key='book_image' 
WHERE p.post_parent='".$current_page_id."' AND
     p.post_status='publish'

The problem in your WHERE condition 您的WHERE状况中的问题

and pm.meta_key='book_image' 

If pep_postmeta have no data, pm.meta_key value in your selection will be NULL So, you should remove this condtion or rewrite it to something like this 如果pep_postmeta没有数据,则您选择的pm.meta_key值将为NULL。因此,您应该删除此条件或将其重写为类似的内容

and (pm.meta_key='book_image' or pm.meta_key IS NULL)

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

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