mysql复杂的内连接多对多

时间:2015-12-11 10:04:32

标签: mysql join inner-join

我有7个表db_categorydb_citydb_localitydb_shopdb_shop_localitydb_shop_recommendeddb_shop_views。< / p>

db_category

category_id    category_name    publish
    1             Apparel          1

db_city

city_id        city_name        publish
   1           bangalore           1

db_locality

locality_id     locality_name     publish
    1            kalyan nagar       1
    2            Madiwala           1

db_shop

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. db_shop时显示publish=1的所有行,并db_category加入db_citydb_localitydb_shop

  2. {li>

    db_shop_recommended priority=1首先出现,等等。

  3. shop_id不在db_shop_recommendedshop_id不在db_shop_recommended来自db_shop_views 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`) 获得更多观看次数。< / p>

  4. 我的结果应如下所示,

    DataSource

    我不知道如何加入和统计视图。是否可以加入上述方法。

1 个答案:

答案 0 :(得分:1)

经过大量搜索。最后我得到了答案。

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 FROM 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 inner join (select max(s.cnt) max_cnt from(select distinct shop_id, count(shop_id) cnt from 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