【问题标题】:MySQL join - ordering results via another table PHPMySQL join - 通过另一个表 PHP 排序结果
【发布时间】:2013-04-26 07:45:47
【问题描述】:

我有 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    

基本上,我要做的是从item_names 表中提取带有特定menu_idsection_id 的每道菜,并根据link_extras 表中的sort 列对输出进行排序。

到目前为止:

$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

不幸的是,无法正确订购。

【问题讨论】:

  • 第二张表中没有apple的记录
  • dish_id = 25link_extras 表中不可用时,为什么Apples 会出现在您的结果中?
  • 对不起我的错误 - 将编辑
  • 对此感到抱歉-但它更准确地代表了link_extras 表配置-这使section_id 列发挥了作用,因为最终我需要获取响应每个部分的信息。给编辑带来不便,敬请见谅
  • @Sideshow - 是的,我知道你为什么在这种情况下使用a.menu_id='1' AND a.section_id='2'。所以现在你的问题是有效的。 :)

标签: php mysql join


【解决方案1】:

你需要使用一个简单的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 |

See this SQLFiddle

【讨论】:

    【解决方案2】:
    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
    

    Demo Here

    输出

    | ITEM_NAME |
    -------------
    |      Fish |
    |     Chips |
    |       Pie |
    |    Onions |
    

    【讨论】:

      猜你喜欢
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多