简体   繁体   English

MySQL - 按另一个表中的列排序

[英]MySQL - order by a column from another table

I have those two tables: 我有这两个表:

Table 1: option_value 表1: option_value

| option_value_id | option_id | sort_order |
|=================|===========|============|
| 1               | 1         | 1          |
| 2               | 1         | 2          |
| 3               | 1         | 3          |

Table 2: option_value_description 表2: option_value_description

| option_value_id | option_id | name   |
|=================|===========|========|
| 1               | 1         | Small  |
| 2               | 1         | Medium |
| 3               | 1         | Large  |

And this code is sorting the results according the "sort_order" values from the "Table 1": 此代码根据“表1”中的“sort_order”值对结果进行排序:

$option_value_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "option_value WHERE option_id = '" . (int)$option_id . "' ORDER BY sort_order ASC");

How can I keep the same code for showing the results, but sort the results by "name" from the Table 2? 如何保持显示结果的相同代码,但是按表2中的“名称”对结果进行排序?

You need to JOIN the two tables on the option_value_id field: 您需要在option_value_id字段上JOIN两个表:

select ovd.*
from option_value ov
   join option_value_description ovd on ov.option_value_id = ovd.option_value_id
where ov.option_id = ?
order by ovd.name

您可以使用INNER JOIN查询,这样您就可以加入表格,并且可以按第二个表的列name进行排序

$option_value_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "option_value a LEFT JOIN " . DB_PREFIX . "option_value_description b ON a.option_id = b.option_id AND a.option_value_id = b.option_value_id WHERE a.option_id = '" . (int)$option_id . "' ORDER BY v.name ASC");

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

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