1

我有 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_idsection_id根据表中的列item_names对输出进行排序。sortlink_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

不幸的是,无法让订单正确。

4

2 回答 2

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 |

看到这个 SQLFiddle

于 2013-04-26T07:56:24.713 回答
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 |
于 2013-04-26T07:56:25.807 回答