gpt4 book ai didi

mysql复杂的多对多内部连接

转载 作者:行者123 更新时间:2023-11-28 23:42:00 24 4
gpt4 key购买 nike

我有 7 个表 db_categorydb_citydb_localitydb_shopdb_shop_localitydb_shop_recommendeddb_shop_views

数据库类别

category_id    category_name    publish
1 Apparel 1

数据库城市

city_id        city_name        publish
1 bangalore 1

数据库位置

locality_id     locality_name     publish
1 kalyan nagar 1
2 Madiwala 1

数据库商店

shop_id   category_id   city_id   locality_id   shop_name   publish
1 1 1 1 name 1
2 1 1 2 name1 1
3 1 1 1 name2 1
4 1 1 1 name3 1

db_shop_recommended

recommended_id     category_id     shop_id    priority    publish
1 1 1 1 1
2 1 2 2 1

db_shop_views

views_id    shop_id    ip_addr    publish
1 1 127.0.0.1 1
2 2 ::1 1
3 4 127.0.0.1 1
4 4 ::1 1
5 3 ::1 1

我想加入以上所有表格。加入的条件是,

  1. publish=1 时显示db_shop 中的所有行并加入db_categorydb_citydb_localitydb_shop

  2. db_shop_recommended 中,priority=1 优先,依此类推。

  3. shop_id不在db_shop_recommended中,从db_shop_views中统计shop_id不在db_shop_recommended 谁的 shop_id 获得了更多浏览量。

我的结果应该如下所示,

shop_id   category_name   city_name   locality_name   shop_name
1 Apparel bangalore kalyan nagar name (result based on `db_shop_recommended` who's priority is more)
2 Apparel bangalore Madiwala name1 (result based on `db_shop_recommended` who's priority is more)
4 Apparel bangalore kalyan nagar name4 (result based on `db_shop_views` who's view count is more)
3 Apparel bangalore kalyan nagar name3 (result based on `db_shop_views`)

我不知道如何加入和计算观看次数。以上方法是否可以加入。

最佳答案

经过大量搜索。我终于得到了答案。

SELECT DISTINCT s.shop_id, c.city_name, l.locality_name, ca.category_name, s.shop_name, s.shop_logo, s.cart_url, s.shop_about 来自 db_shop s INNER JOIN db_city c ON c.city_id = s.city_id INNER JOIN db_category ca ON ca.category_id = s.category_id INNER JOIN db_locality l ON l.locality_id = s.locality_id LEFT JOIN (SELECT * FROM db_shop_recommended r ORDER BY r.priority ASC) r1 ON s.shop_id = r1 .shop_id LEFT JOIN (select distinct g.shop_id, g.cnt from (select distinct shop_id, count(shop_id) cnt from db_shop_views group by shop_id) g 内连接(select max(s.cnt) max_cnt from(select distinct shop_id, count (shop_id) cnt 来自 db_shop_views group by shop_id) s) m on m.max_cnt = g.cnt) v ON s.shop_id = v.shop_id WHERE s.publish = 1

关于mysql复杂的多对多内部连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34220795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com