我有两张桌子。
表1:wp_pc_products

feed_product_name     id_merchant
    sony xperia c3        fkt
    nokia lumia           fkt
    samsung galaxy        fkt
    sony xperia c3        snd
    nokia lumia           snd
    samsung galaxy        snd


表2:wp_pc_products_merchants

slug     image
fkt      logo1.png
snd      logo2.png


这两个表之间的关系是wp_pc_products中的id_merchant和wp_pc_products_merchant中的slug具有相同的记录,但在第二个表中不同。

我现有的查询是

select p.feed_product_name,p.id_merchant,m.image from wp_pc_products p JOIN wp_pc_products_merchants m ON m.slug=p.id_merchant where (feed_product_name like'sony%' or feed_product_name like'%xperia%' or feed_product_name like'%c3%') and (p.price BETWEEN "629.3" and "1168.7"


如果我在此查询的末尾使用group by子句作为(group by id_merchant),则查询未给我预期的结果。

我也尝试过此查询及其工作正常,但我在上述查询中希望使用的方式相同。

SELECT  wp_pc_products.*,wp_pc_products_merchants.image FROM wp_pc_products JOIN wp_pc_products_merchants ON wp_pc_products.id_merchant = wp_pc_products_merchants.slug  WHERE feed_product_name LIKE '%sony%' and feed_product_name LIKE '%xperia%' and feed_product_name LIKE '%c3%' group by id_merchant


我的预期结果是:

sony xperia c3    fkt     logo1.png
sony xperia c3    snd     logo2.png

最佳答案

这是使用技术组明智的最大http://dev.mysql.com/doc/refman/5.7/en/example-maximum-column-group-row.html的方法

select
wpp1.feed_product_name,
wpp1.id_merchant,
wpm.image
from wp_pc_products wpp1
join (
  select min(id_product) as id_product,id_merchant
  from wp_pc_products group by id_merchant
)wpp2 on wpp2.id_product = wpp1.id_product
join wp_pc_products_merchants wpm on wpm.slug = wpp1.id_merchant

10-07 19:52
查看更多