mySQL:根据键/值表中的几个键进行选择

时间:2015-02-02 21:17:40

标签: php mysql wordpress

我正在使用Wordpress并尝试从我自己的一个表中选择与本机wp_postmeta表中的值对应的值。

我的桌子被称为“wellwishertable”,我想从wellwisher表中找到所有ID(所以我可以算一下)......

1)wellwishertable'aliatedID'字段位于wp_postmeta post_id

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

3)wellwishertable'许可'正在等待

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

5)wp_postmeta meta_key'冻结'不等于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') );

这似乎“几乎”有效,除了它不计算wp_postmeta表中没有“冻结”meta_key的记录。我想让它计算任何未被“冻结”的记录,无论它是否存在(只要'状态'不是'打开')。

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

1 个答案:

答案 0 :(得分:1)

LEFT JOIN上使用INNER JOIN代替mt2,因为INNER JOIN只返回在那里有条目的结果。

为避免要求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