mySQL:根据key/value中的几个键选择 table

mySQL: selecting based on several keys in key/value table

我正在使用 Wordpress 并尝试 select 来自我自己的 table 的值,这些值对应于本机 wp_postmeta table.

我的 table 叫做 "wellwishertable",我想从祝福者 table 那里找到所有的 ID(这样我就可以数一数)...

1) 祝福者table 'associatedID' 字段在 wp_postmeta post_id

2) wellwishertable 'associatedAuthorID' 与 $userID 变量相同

3) 祝福者table 'permission' 待定

4) wp_postmeta meta_key 'status' 不等于 meta_value 'open'

5) wp_postmeta meta_key 'freeze' 不等于 meta_value 'frozen'

我已经走到这一步了...

    "SELECT DISTINCT wellwisher.ID FROM wellwishertable wellwisher 
    INNER JOIN wp_postmeta ON (wellwisher.associatedID = wp_postmeta.post_id) 
    INNER JOIN wp_postmeta AS mt1 ON (wp_postmeta.post_id = mt1.post_id) 
    INNER JOIN wp_postmeta AS mt2 ON (wp_postmeta.post_id = mt2.post_id) 

    WHERE wellwisher.associatedAuthorID=".$userID." 
    AND wellwisher.permission ='pending' 
    AND ( (mt1.meta_key = 'status' AND mt1.meta_value != 'open') AND 
          (mt2.meta_key = 'freeze' AND mt2.meta_value != 'frozen') );

这似乎是 'nearly' 工作,除了它不计算 wp_postmeta table 中没有 "freeze" meta_key 的记录.我希望它计算任何不是 "frozen" 的记录,无论它是否存在(只要 'status' 不是 'open')。

有人能给我指出正确的方向吗?

mt2 上使用 LEFT JOIN 而不是 INNER JOIN,因为 INNER JOIN 只会 return 有条目的结果。

为了避免要求 mt2.meta_key 总是必须等于 freeze,请将该条件移至连接中的 ON 子句。

您也可以考虑直接在查询中使用 COUNT 而不是稍后再弄清楚:

"SELECT COUNT(DISTINCT wellwisher.ID) FROM wellwishertable wellwisher 
INNER JOIN wp_postmeta ON (wellwisher.associatedID = wp_postmeta.post_id) 
INNER JOIN wp_postmeta AS mt1 ON (wp_postmeta.post_id = mt1.post_id) 
LEFT JOIN wp_postmeta AS mt2 ON (wp_postmeta.post_id = mt2.post_id) 
    AND mt2.meta_key = 'freeze'

WHERE wellwisher.associatedAuthorID=".$userID." 
AND wellwisher.permission ='pending' 
AND ( (mt1.meta_key = 'status' AND mt1.meta_value != 'open') AND 
      (mt2.meta_value != 'frozen') );

重要提示:$userID 直接转储到查询字符串中可能是一个很大的安全问题。请考虑使用 parameterized queries.