[英]Wordpress MySQL query with WHERE clause after GROUP_CONCAT returns unexpected results
SELECT p.*,
GROUP_CONCAT(pm.meta_key ORDER BY pm.meta_key DESC SEPARATOR '||') as meta_keys,
GROUP_CONCAT(pm.meta_value ORDER BY pm.meta_key DESC SEPARATOR '||') as meta_values
FROM $wpdb->posts p
LEFT JOIN $wpdb->postmeta pm on pm.post_id = p.ID
WHERE p.post_type = 'item' and p.post_status = 'publish'
AND pm.meta_key = 'adtype'
AND pm.meta_value = '1'
GROUP BY p.ID
ORDER BY p.post_date_gmt DESC
LIMIT 0,10
I'm using a special WordPress query to get post and postmeta data and ran into a problem when I wanted to add an additional WHERE on the postmeta. 我正在使用特殊的WordPress查询来获取发布和发布后的数据,当我想在postmeta上添加其他WHERE时遇到问题。
Here I want to limit results where pm.meta_key adtype is equal to 1. The query works, but var_dump() shows that it changes the value of the group concatenated meta_keys and meta_values. 在这里,我想限制pm.meta_key adtype等于1的结果。该查询有效,但是var_dump()表明它更改了串联的meta_keys和meta_values组的值。
In my results I no longer get meta_keys and meta_values out as concatenated results, rather they get set to the WHERE values of 'adtype' and '1' respectively. 在我的结果中,我不再将meta_keys和meta_values作为连接结果取出,而是将它们分别设置为'adtype'和'1'的WHERE值。
The query works without the additional WHERE clauses, but I would like the ability to filter results. 该查询无需附加WHERE子句即可工作,但我希望能够过滤结果。
It's normal, when you add the WHERE
clause : 添加WHERE
子句是正常的:
AND pm.meta_key = 'adtype'
AND pm.meta_value = '1'
you are limiting the result to only the rows that have these values, so in your meta_keys & meta_values your won't have values that differ from those specified in the WHERE
clause. 您将结果限制为仅具有这些值的行,因此,在meta_keys和meta_values中,您的值将不会与WHERE
子句中指定的值不同。
I found the solution myself in this thread: Can't get a complicated mysql query to work 我自己在以下线程中找到了解决方案: 无法使复杂的mysql查询正常工作
In the SELECT statement I gave a new value for adtype with: 在SELECT语句中,我为adtype提供了一个新值:
max(case when pm.meta_key='adtype' then pm.meta_value end) as adtype max(如果pm.meta_key ='adtype'然后pm.meta_value结束的情况)作为adtype
And after GROUP BY I added: 在GROUP BY之后,我添加了:
HAVING adtype = '1' 广告类型=“ 1”
This worked! 这工作了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.