我有2个MySQL表,其中一个有一个数字列,用于指示我需要显示的项目的顺序:
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
基本上我要做的是从表格menu_id
中提取每个菜单section_id
和item_names
,并根据sort
列排序输出在link_extras
表中。
到目前为止:
$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
不幸的是,只是无法使订单正确。
答案 0 :(得分:2)
您需要使用简单的JOIN
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 |
答案 1 :(得分:1)
SELECT
in.item_name
FROM item_names AS in
LEFT JOIN link_extras AS le
ON le.dish_id = in.dish_id
WHERE in.menu_id = 1
AND in.section_id = 2
ORDER BY le.sort
输出
| ITEM_NAME |
-------------
| Fish |
| Chips |
| Pie |
| Onions |