简体   繁体   English

MySQL-仅当在同一张表中但不同行中没有设置获胜者时,才选择帖子ID。 随附示例代码

[英]MySQL - select post ID only if there is no winner set in the same table, but different row. Sample code included

I have a wordpress table wp_postmeta and what I want is a list of all posts where sttf_split_test_status = 'active' but it CAN NOT have another meta row with the same post_id and a meta_key of stti_winner set. 我有一个wordpress表wp_postmeta,我想要的是sttf_split_test_status = 'active'的所有帖子的列表,但它不能有另一个具有相同post_id和meta_key的stti_winner set的元行。 My below code returns empty, but there should be a result. 我的以下代码返回空,但应该有结果。

SELECT DISTINCT post_id 
FROM wp_postmeta 
WHERE meta_key = 'sttf_split_test_status' 
  AND meta_value = 'active' 
  AND NOT EXISTS (
    SELECT post_id 
    FROM wp_postmeta 
    WHERE post_id = post_id 
    AND meta_key = 'stti_winner'
  )
LIMIT 0, 25

Try 尝试

SELECT DISTINCT yes.post_id
FROM wp_postmeta AS yes
LEFT JOIN wp_postmeta AS no 
  ON yes.post_id=no.post_id
  AND no.meta_key='stti_winner'
WHERE yes.meta_key = 'sttf_split_test_status' 
AND yes.meta_value = 'active' 
AND no.post_id IS NULL
LIMIT 0, 25
;

Explanation: To every fitting record we try to join the corresponding 'stti_winner'. 说明:对于每个拟合记录,我们尝试加入相应的“ stti_winner”。 Only if that fails (fields of LEFT JOIN stay NULL ), we accept the record. 只有失败( LEFT JOIN字段保持NULL ),我们才接受记录。

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

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