简体   繁体   English

如何从另一个表进行内部联接并按特定的行值排序?

[英]How to inner join from another table and order by specific row value?

In WordPress, there are 2 tables: wp_terms and wp_termmeta. 在WordPress中,有2个表:wp_terms和wp_termmeta。

I currently do the following to get the terms and parents etc: 我目前正在执行以下操作以获取条款和父母等:

$query = mysqli_query($mysqli, "
SELECT wp_terms.term_id,wp_terms.name, wp_term_taxonomy.parent
FROM wp_terms INNER JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
WHERE wp_term_taxonomy.taxonomy = 'post-categories'
ORDER BY name"); 

However - I need to access the wp_termmeta table, select a row where the term_id is the same and the meta_key is "order" then order by the meta_value of the wp_termmeta, instead of name as it is currently. 但是-我需要访问wp_termmeta表,选择term_id相同且meta_key为“ order”的行,然后按wp_termmeta的meta_value而不是当前的名称进行排序。

How would I do that with the current query? 如何使用当前查询执行此操作?

I don't have wordpress-specific knowledge, but according to your description the query could look like this (I added table aliases for readability, but they are not necessary): 我没有特定于wordpress的知识,但是根据您的描述,查询可能看起来像这样(我添加了表别名以提高可读性,但这不是必需的):

SELECT t.term_id, t.name, tax.parent
FROM wp_terms t
INNER JOIN wp_term_taxonomy tax ON t.term_id = tax.term_id
INNER JOIN wp_termmeta m ON m.term_id = t.term_id AND m.meta_key = 'order'
WHERE tax.taxonomy = 'post-categories'
ORDER BY m.meta_value

The most interesting part here is the join condition of the second join, which contains two conditions: m.term_id = t.term_id AND m.meta_key = 'order' It first makes sure the term ids are matching and then assures that the meta key of the joined row is actually "order". 这里最有趣的部分是第二个m.term_id = t.term_id AND m.meta_key = 'order'条件,其中包含两个条件: m.term_id = t.term_id AND m.meta_key = 'order'首先确保项ID匹配,然后确保元键所连接的行中的实际上是“订单”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM