【问题标题】:Mysql INNER JOIN sub table with comma separated values from main table columnMysql INNER JOIN 子表与主表列中的逗号分隔值
【发布时间】:2020-11-05 01:30:33
【问题描述】:

我想在 products 表中加入来自 daily_discounts.discount_product 表限制 1 的最后插入的逗号分隔值。有可能在一个查询中实现这一点吗?

试过了:

SELECT * FROM `daily_discounts` INNER JOIN products WHERE FIND_IN_SET(products.product_id , daily_discounts.discount_products)

SELECT * FROM `daily_discounts` INNER JOIN products ON FIND_IN_SET(products.product_id , daily_discounts.discount_products) LIMIT 1

表daily_discounts:

+-------------+---------------------+
| discount_id | discount_products   |
+-------------+---------------------+
| 1           | 960,310,165,702     |
+-------------+---------------------+
| 2           | 231,822,379,420     |
+-------------+---------------------+
| 3           | 518,56,803,858      |
+-------------+---------------------+

想要的表格产品结果:

+------------+--------------------+
| product_id | product_sale_price |
+------------+--------------------+
| 518        | 10.25              |
+------------+--------------------+
| 56         | 11.24              |
+------------+--------------------+
| 803        | 5.55               |
+------------+--------------------+
| 858        | 13.52              |
+------------+--------------------+

为了工作,我使用了两个查询 首先,我选择 daily_discounts 表中最后插入的记录:

select `discount_products` from `daily_discounts` order by `discount_id` desc limit 1

第二我选择产品表

select `product_id`, `product_sale_price from `products` where `product_id` in (518, 56, 803, 858) order by `product_id` desc)

【问题讨论】:

标签: mysql sql


【解决方案1】:

您可以尝试使用 row_number()

select * from
(
SELECT *,row_number() over(order by discount_id desc) as rn
FROM `daily_discounts` 
)A
INNER JOIN products WHERE FIND_IN_SET(products.product_id,A.discount_products) and rn=1

【讨论】:

  • 太棒了,有效:) 谢谢,
【解决方案2】:

如果“最新”行是 discount_id 值最高的行,假设 discount_id 是唯一标识符(或主键)

SELECT p.product_id
     , p.product_sale_price
  FROM ( -- inline view to get identifier of latest row 
         SELECT MAX(l.discount_id) AS latest_discount_id 
           FROM `daily_discounts` l
       ) m
  JOIN `daily_discounts` d
    ON d.discount_id = m.latest_discount_id
  JOIN `products` p
    ON FIND_IN_SET(p.id,d.discount_products)
 ORDER
    BY FIND_IN_SET(p.id,d.discount_products)
    
    

如果我们需要对行进行排序的其他列或表达式,以确定哪些行符合条件以及哪些是最新的,我们可以修改内联视图查询

SELECT p.product_id
     , p.product_sale_price
  FROM ( -- inline view to get identifier of latest row 
         SELECT l.discount_id AS latest_discount_id 
           FROM `daily_discounts` l
          WHERE ... 
          ORDER BY ...
          LIMIT 1
       ) m
  JOIN `daily_discounts` d
    ON d.discount_id = m.latest_discount_id
  JOIN `products` p
    ON FIND_IN_SET(p.id,d.discount_products)
 ORDER
    BY FIND_IN_SET(p.id,d.discount_products)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多