如何使用group by
或其他方法从我的多个表格中选择记录并限制每个卖方的记录数。我知道这可能是重复的问题,但我也尝试了很多示例,但在我的情况下都无济于事。
我已经尝试完成此查询超过4天,但仍然没有运气。请任何人帮我,我也在这里http://sqlfiddle.com/#!9/7a9d62/5
添加了sqlfiddle参考。以下是我最后尝试执行的操作,但仍无法正常工作。我也确实在此处发布了有关堆栈溢出的问题,但我没有得到答案How to limit number of record using mysql group by and inner join for multiple tables
SELECT p.product, p.p_id, p.p_store_key, p.p_seller_key, st.store, sl.seller,
SQRT(POW(69.1 * (st.st_lat - 2.922461), 2) + POW(69.1 * (101.639587 - st.st_lng) * COS(st.st_lat / 57.3), 2)) AS distance
FROM dbt_product AS p
INNER JOIN dbt_sellers AS sl
ON p.p_seller_key = sl.s_id
INNER JOIN dbt_stores AS st
ON st.st_id = p.p_store_key
WHERE (
SELECT COUNT(*)
dbt_product AS pl
WHERE pl.p_id = p.p_id
) <= 2
HAVING distance <= 25
ORDER BY sl.s_id DESC
产品表
product | p_id | p_store_key | p_seller_key
----------|--------|----------------------|----------------
dog | 100 | MT66 | SE100
bird | 101 | MT67 | SE100
cow | 103 | MT66 | SE100
cat | 104 | MT66 | SE100
goat | 105 | QR89 | NK100
cow | 106 | QR89 | NK100
cat | 107 | QR89 | NK100
cat | 108 | GK59 | MB100
rat | 109 | GK15 | MB100
fish | 110 | UI100 | VX100
产品存储表
store | st_id | st_lng | st_lat
----------------|-----------|------------|--------------------
SellPoint | MT66 | 00.0000 | 00.0000
Sell days | MT67 | 00.0000 | 00.0000
payNGo | QR89 | 00.0000 | 00.0000
CashPoin | GK15 | 00.0000 | 00.0000
FastSell | VX100 | 00.0000 | 00.0000
卖家表
seller | s_id
----------------|-------------------
Peter | SE100
John | NK100
Hana | MB100
Alice | UI100
预期结果
product | p_id | p_store_key | p_seller_key
---------|--------|---------------|-------------------------------
dog | 100 | MT66 | SE100
bird | 101 | MT67 | SE100
goat | 105 | QR89 | NK100
cow | 106 | QR89 | NK100
cat | 108 | GK59 | MB100
rat | 109 | GK15 | MB100
fish | 110 | UI100 | VX100
请我确实确实需要帮助,我知道可以存档,但是我不知道该怎么做。
答案 0 :(得分:0)
您可以使用ROW_NUMBER()
SELECT *
FROM (
SELECT *
, ROW_NUMBER() OVER(PARTITION BY p_seller_key ORDER BY p_seller_key) AS rn
FROM dbt_product p
) a
WHERE rn <= 2
https://www.db-fiddle.com/f/5A6YnhdQGkBHFthiobYM6B/0
添加JOIN
SELECT p.*
, SQRT(POW(69.1 * (st.st_lat - 2.922461), 2) + POW(69.1 * (101.639587 - st.st_lng) * COS(st.st_lat / 57.3), 2)) AS distance
FROM (
SELECT *
, ROW_NUMBER() OVER(PARTITION BY p_seller_key ORDER BY p_seller_key) AS rn
FROM dbt_product p
) p
INNER JOIN dbt_sellers sl ON p.p_seller_key = sl.s_id
INNER JOIN dbt_stores st ON st.st_id = p.p_store_key
WHERE rn <= 2
AND SQRT(POW(69.1 * (st.st_lat - 2.922461), 2) + POW(69.1 * (101.639587 - st.st_lng) * COS(st.st_lat / 57.3), 2)) < 25
ORDER BY sl.s_id DESC