MySQL连接-通过另一个PHP表对结果进行排序
我有两个MySQL表,其中一个表有一个数字列来组织我需要显示的项目的顺序:MySQL连接-通过另一个PHP表对结果进行排序,php,mysql,join,Php,Mysql,Join,我有两个MySQL表,其中一个表有一个数字列来组织我需要显示的项目的顺序: item_names menu_id | dish_id | section_id | item_name -------------------------------------------------- 1 | 23 | 2 | Pie 1 | 24 | 2 | Fish
item_names
menu_id | dish_id | section_id | item_name
--------------------------------------------------
1 | 23 | 2 | Pie
1 | 24 | 2 | Fish
1 | 25 | 3 | Apples
1 | 26 | 2 | Onions
1 | 27 | 2 | Chips
link_extras
extra_id | dish_id | sort
-----------------------------
1 | 23 | 2
2 | 23 | 2
3 | 23 | 2
1 | 24 | 0
5 | 24 | 0
6 | 26 | 3
12 | 26 | 3
1 | 27 | 1
1 | 25 | 0
基本上,我试图做的是从表项目名称中提取具有特定菜单id
和节id
的每个菜,并根据链接附加表中的排序列对输出进行排序
到目前为止:
$query="SELECT a.item_name, a.dish_id, b.sort
FROM item_names AS a, link_extras AS b
WHERE a.menu_id='1'
AND a.section_id='2'
AND b.dish_id=a.dish_id
GROUP BY b.dish_id
ORDER BY b.sort";
我对数据库还不熟悉,所以如果有任何帮助,我将不胜感激。我追求的结果是
Fish
Chips
Pie
Onions
不幸的是,无法获得正确的顺序。您需要使用一个简单的连接
SELECT a.item_name, a.dish_id, b.sort
FROM item_names AS a
JOIN link_extras AS b
ON a.dish_id = b.dish_id
WHERE menu_id = 1
AND section_id = 2
GROUP BY b.dish_id
ORDER BY b.sort
输出:
| ITEM_NAME | DISH_ID | SORT |
------------------------------
| Fish | 24 | 0 |
| Chips | 27 | 1 |
| Pie | 23 | 2 |
| Onions | 26 | 3 |
输出
| ITEM_NAME |
-------------
| Fish |
| Chips |
| Pie |
| Onions |
第二张表中没有苹果的记录为什么当dish\u id=25
在表link\u extras
中不可用时,Apples
会出现在您的结果中?对不起,我犯了错误-威尔·伊迪茨对此表示抱歉-但它更准确地表示了link\u extras
表配置-这将发挥作用section\u id
列,因为我最终需要获得每个部分的响应信息。很抱歉给您带来不便edit@Sideshow-是的,我知道为什么在条件中使用a.menu\u id='1'和a.section\u id='2'
。现在你的问题是正确的
| ITEM_NAME |
-------------
| Fish |
| Chips |
| Pie |
| Onions |