Set MySQL variables in WPDB

时间:2021-01-24 作者:Steven Hardy

我有一个SQL查询,它可以很好地作为原始SQL查询工作,但是当我将其放入WPDB时,它会抛出一个错误:

global $wpdb;

    $sql = "SET @product_group = (SELECT product_group FROM insert_temporary LIMIT 1);

SELECT * FROM insert_temporary 
WHERE product_group in (SELECT product_group FROM insert_temporary
                WHERE product_group = @product_group
              GROUP BY product_group
              HAVING COUNT(product_group) > 1)";

    $data = $wpdb->get_results($sql);
这是错误:

WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'SELECT * FROM insert_temporary WHERE product_group in (SELECT product_group FRO\' at line 3]
SET @product_group = (SELECT product_group FROM insert_temporary LIMIT 1); SELECT * FROM insert_temporary WHERE product_group in (SELECT product_group FROM insert_temporary WHERE product_group = @product_group GROUP BY product_group HAVING COUNT(product_group) > 1)
请问如何在WPDB中设置MySQL变量,以便将两者结合使用?

1 个回复
SO网友:Steven Hardy

我真傻。最后,我设置了一个所需的PHP变量,而不是@设置“”;。我的最终代码是:

$group_sql = "SELECT product_group FROM insert_temporary LIMIT 1";
    $group = $wpdb->get_var($group_sql);

    $sql = "SELECT * FROM insert_temporary 
WHERE product_group in (SELECT product_group FROM insert_temporary WHERE product_group = \'". $group ."\' GROUP BY product_group HAVING COUNT(product_group) > 1)";

    $results = $wpdb->get_results($sql);
这可能会帮助某人:)