连接两次后置表的查询

时间:2014-05-20 作者:RailsTweeter

我相信我所做的对于标准来说太复杂了meta_query 中的参数get_posts, 因此,我尝试使用自定义SQL查询执行以下操作:

我有一个游戏自定义帖子,其中包含team1和team2的自定义字段,存储为Posteta。给定团队XXXX,我需要为Posteta key team1或Posteta key team2提取所有Posteta值为XXXX的帖子。

我还需要考虑今年的情况,因为每年都有两队可以相互比赛。游戏帖子类型的年份存储为Posteta年份。

我尝试使用以下内容(在phpmyadmin中进行测试),但它不起作用。。。

我在这里的两个变量是年=2014和队=洋基队:

SELECT DISTINCT (p.ID), p.post_title
FROM wp_posts p
JOIN wp_postmeta pm1 ON p.ID = pm1.post_id
JOIN wp_postmeta pm2 ON p.ID = pm2.post_id
WHERE 1 =1
AND p.post_type =  \'game\'
AND ((pm1.meta_key =  \'year\'
 AND pm1.meta_value =  \'2014\'
 AND pm2.meta_key =  \'team1\'
 AND pm2.meta_value =  \'yankees\') OR
(pm1.meta_key =  \'year\'
 AND pm1.meta_value =  \'2014\'
 AND pm2.meta_key =  \'team2\'
 AND pm2.meta_value =  \'yankees\'))

2 个回复
SO网友:s_ha_dum

“我的SQL不工作”问题很难回答,因为如果没有OP的数据集,它们几乎是不稳定的,但是。。。

我想你可能把事情弄得太复杂了。

SELECT 
  DISTINCT (p.ID), 
  p.post_title
FROM wp_posts p
JOIN wp_postmeta pm1 ON p.ID = pm1.post_id
JOIN wp_postmeta pm2 ON p.ID = pm2.post_id
WHERE 1 = 1
AND p.post_type =  \'game\'
AND (
  pm1.meta_key =  \'year\' 
  AND pm1.meta_value = \'2014\'
) 
AND (
  pm2.meta_key IN (\'team1\',\'team2\')
  AND pm2.meta_value =  \'yankees\'
)
我想这可以满足你的需要。是的,我很确定你不能用WP_Query 直接,但是。。。

function swap_key_wpse_144950($where) {
  remove_filter(\'posts_where\',\'swap_key_wpse_144950\');
  $where = str_replace("= \'xxteamsxx\'"," IN (\'team1\',\'team2\')",$where);
  return $where;
}
add_filter(\'posts_where\',\'swap_key_wpse_144950\');

$args = array(
  \'meta_query\' => array(
    array(
      \'key\' => \'year\',
      \'value\' => \'2014\'
    ),
    array(
      \'key\' => \'xxteamsxx\',
      \'value\' => \'yankees\'
    )
  )
);
$q = new WP_Query($args);
var_dump($q->request);

SO网友:Blerta

您是否可以尝试将此查询编写为

SELECT DISTINCT (p.ID), p.post_title
FROM wp_posts p
left outer join wp_postmeta pm1 ON p.ID = pm1.post_id AND pm1.meta_key = \'team1\' and pm1.meta_value =  \'yankees\'
left outer join wp_postmeta pm2 ON p.ID = pm2.post_id  and pm2.meta_key =  \'team2\'  and pm2.meta_value =  \'yankees\'
left outer join wp_postmeta pm on p.ID= pm.post_id and pm.meta_key = \'year\' and pm.meta_value = \'2014\'
WHERE p.post_type =  \'game\'
你不需要把条件设为1=1,因为你有很多其他where子句(不需要假子句)。让我知道结果

编辑

这个怎么样

SELECT DISTINCT (p.ID), p.post_title
FROM wp_posts p
left outer join wp_postmeta pm1 ON p.ID = pm1.post_id AND pm1.meta_key = \'team1\' 
left outer join wp_postmeta pm2 ON p.ID = pm2.post_id  and pm2.meta_key =  \'team2\'  
left outer join wp_postmeta pm on p.ID= pm.post_id and pm.meta_key = \'year\' 
WHERE p.post_type =  \'game\'  and pm.meta_value = \'2014\' and (pm1.meta_value = \'yankees\' or pm2.meta_value = \'yankees\')

结束

相关推荐

为什么dbDelta()不能捕获MysqlErrors?

据我所见,dbDelta() 用于抑制在其操作过程中发生的数据库错误。一般来说,情况似乎是这样,但New Relic仍在报告函数中的MysqlErrors。准确的错误消息格式如下:MysqlError: Table \'xxx.wp_yyy_posts\' doesn\'t exist 发件人dbDelta() 在里面/wp-admin/includes/upgrade.php, 我们有:// Fetch the table column structure from the database&