首页 > 解决方案 > Variables in SQL queries

问题描述

In the below query I noticed these named variables wposts, wpostmeta and was wondering how they work and what are they called (MySQL variables) so I can find out more information about using them in the MySQL docs.

Is it a shorthand so you don't have to type $wpdb->postmeta every time or is there more to this? Also, I don't understand the SELECT wposts.* there is no Wordpress table called wposts so what are you selecting from?

https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query

$querystr = "
        SELECT wposts.* 
        FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
        WHERE wposts.ID = wpostmeta.post_id 
        AND wpostmeta.meta_key = 'custom-key' 
        AND wposts.post_type = 'page' 
        ORDER BY wpostmeta.meta_value DESC
 ";

标签: phpmysqlwordpress

解决方案


它们是表别名,并且(通常)提供了一种在查询中引用表的简写方式。在您的查询中,名称为 的表现$wpdb->posts在称为wposts,而调用$wpdb->postmeta的表现在称为wpostmeta。请注意,一旦您声明了一个别名,您必须使用该别名引用该表,因此在您的查询中您有对wposts.*等的引用wpostmeta.meta_value

请注意,您还可以使用列别名,例如:

SELECT SUM(x) AS total FROM t1

另请注意,AS我在上面的列选择中显示的关键字是可选的,可用于表和列别名。

您可以在此处阅读有关别名的更多信息。


推荐阅读