简体   繁体   English

SQL连接表2条语句的结果

[英]SQL join table result of 2 statements

I am trying to get data with SQL from my Wordpress database by a JOIN, but I do not get it working. 我试图通过JOIN从我的Wordpress数据库中获取SQL数据,但无法正常工作。

What I need: 我需要的:

  • Posts where the meta_key "gtp_product_dont_show" exists and where the meta_value not is "true". 发布meta_key“ gtp_product_dont_show”存在且meta_value不为“ true”的地方。
  • And posts where the meta_key "gtp_product_dont_show" does not exists. 并张贴meta_key“ gtp_product_dont_show”不存在的地方。

My Problem: 我的问题:

I now only get the results where posts have a meta_key "gtp_product_dont_show", but there are also posts which don't have this key, and I need these as well. 现在,我只获得帖子包含meta_key“ gtp_product_dont_show”的结果,但是有些帖子没有此关键字,我也需要这些。

This is what I have now: 这就是我现在所拥有的:

SELECT 
    ID, post_title
FROM 
    wp_posts p
    JOIN wp_postmeta m ON 
        p.ID = m.post_id AND 
        m.meta_key = 'gtp_product_dont_show' AND 
        m.meta_value != 'true'
WHERE 
    post_type = 'products' AND 
    post_status = 'publish'

Output: 输出:

You need a left join : 您需要left join

SELECT ID, post_title
FROM wp_posts p LEFT JOIN
     wp_postmeta m
     ON p.ID = m.post_id AND 
        m.meta_key = 'gtp_product_dont_show' 
WHERE (m.meta_value is null or m.meta_value <> 'true') and
      post_type = 'products' AND 
      post_status = 'publish';

The left join looks for an appropriate key in the wp_postmeta table. left join wp_postmetawp_postmeta表中寻找适当的键。 The where clause then says "keep a record when there is no match or the value is not true" -- which I think is the logic you are looking for. 然后where子句说“在没有匹配项或值不为真时保留记录” –我认为这是您要寻找的逻辑。

You're looking for this? 您在找这个吗?

SELECT 
    ID, post_title
FROM 
    wp_posts p
WHERE 
    post_type = 'products' AND 
    post_status = 'publish' AND
    not exists (
        select 1 
        from wp_postmeta m
        where 
        p.ID = m.post_id AND 
        m.meta_key = 'gtp_product_dont_show' AND 
        m.meta_value = 'true')

This will fetch all the rows from wp_posts, but leave out those where row is found from wp_postmeta where meta_key is gtp_product_dont_show and value is true. 这将从wp_posts中获取所有行,但忽略那些从wp_postmeta中找到行的行,其中meta_key为gtp_product_dont_show且value为true。

You can use the OR operator to consider both conditions. 您可以使用OR运算符同时考虑这两种情况。 Try this: 尝试这个:

SELECT stuff
FROM myTable
JOIN otherTable ON 
   (m.meta_key = 'gtp_product_dont_show' AND m.meta_value != 'true') OR 
   (m.meta_key != 'gtp_product_dont_show')
...

Just a side note, I don't recommend storing booleans as strings like that. 只是附带说明,我不建议将布尔值存储为这样的字符串。 You should consider using a TINYINT() where boolean fields are stored as 0 for false, or 1 for true. 您应该考虑使用TINYINT() ,其中布尔字段存储为0(表示false)或1(表示true)。

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

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