【问题标题】:using "order by" on inner join MySql?在内部连接 ​​MySql 上使用“order by”?
【发布时间】:2011-06-02 17:15:34
【问题描述】:

你好世界各地的大师,我又来这里了:D

现在我想问你一些简单的问题,但我真的是编程和 sql 方面的新手,所以需要更多学习。

好的,让我们来解决问题。我有一些这样的 sql 查询

SELECT
eu_product.*,
eu_shop_display.display_name as dname,
eu_product_img.image_url as img
FROM eu_product
INNER JOIN eu_product_img on eu_product_img.product_id = eu_product.product_id
INNER JOIN eu_shop_display on eu_shop_display.display_id = eu_product.product_display
where eu_product.publish=1
and eu_product.shop_id=1
and eu_product.product_display IN (select display_id from eu_shop_display where parent_id=1) 
or eu_product.product_display = 1
GROUP BY eu_product.product_id 
ORDER BY eu_product.product_id DESC  LIMIT 0, 10

问题出在

INNER JOIN eu_product_img on eu_product_img.product_id = eu_product.product_id

这样的表格

我需要在“listing”字段上使用 Order ASC。

SQL查询是可以使用两个ord​​er by,还是可以在inner join中添加order by?我尝试添加

ORDER BY eu_product.product_id DESC, eu_product_img.listing ASC

但它不起作用:(

也许有人可以解释它的工作原理。


更新

.

这个产品表

这个product_img 表

这是一个结果

但“eu_product_img.listing ASC”运行不正确:(

我需要 product_id 1 上的列表是 1 而不是 4

查看表 product_img

在加入之前,我需要先运行 product_img.listing 订单 ASC。

正确的查询是这样的

SELECT eu_product.product_id, 
(select img.listing from eu_product_img as img where img.product_id = eu_product.product_id order by img.listing ASC limit 1 ) as listing 
    FROM eu_product 
    where eu_product.shop_id=1 
    or eu_product.product_display = 2 
    GROUP BY eu_product.product_id 
    ORDER BY eu_product.product_id DESC  LIMIT 0, 20

所以它不能使用内连接?

之前谢谢。

请注意, 史蒂西

【问题讨论】:

  • 您要按什么排序? product_idlisting? ORDER BY eu_product.product_id DESC, eu_product_img.listing ASC 应该可以工作。在您放置的任何输出函数中,MySQL 排序是否得到尊重?
  • 如果您在此处粘贴所需的输出,您可能会得到更好的响应。

标签: php mysql


【解决方案1】:

它正在工作。从屏幕截图中可以看出,它们首先按 product_id 排序,然后按列表排序。如果您只想通过列表订购,请执行ORDER BY eu_product_img.listing ASC。如果您想通过列表然后产品订购,请通过语句反转您的订购。

Order by 接受多个语句,但您的结果将按照您指定的 order 语句的顺序进行排序 ;) 因此,如果列表在前,则结果将按列表在前排序,等等。

【讨论】:

  • ORDER BY eu_product.product_id DESC, eu_product_img.listing ASC 不同的表:(
  • 我同意这个评论,但排序在 OP 输出中没有正确显示。
  • @Stecy,没关系...您可以按查询中包含的任何表中的任何列进行排序。这是基本的 SQL。
  • 所以当 product_id = 1 时,listing 应该 = 1?您的内部连接定义了这种关系,只要我了解您的列名周围的上下文,您就有权。
  • 是的,像 SELECT eu_product.product_id 这样的正确查询,(选择 img.listing from eu_product_img as img where img.product_id = eu_product.product_id order by img.listing ASC limit 1 ) 作为来自 **... ** 的列表,因此它不能使用内部连接 ​​@brad ???
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 2012-03-10
  • 1970-01-01
  • 2013-01-08
相关资源
最近更新 更多