MySQL使用不同的条件合并来自两个表的数据并排序

时间:2015-07-21 16:27:18

标签: mysql sql database e-commerce

我有两个表,country和country_description。两个表都包含store_id和country_id。

国家/地区

country_row_id,
country_id,
store_id,
status,
date_added,
is_delete

country_description

country_id,
store_id,
language_id,
name,
description

这些表包含store_id = 0的默认值,这意味着默认情况下,所有商店都会看到store_id = 0的结果,但是当他们尝试插入任何新国家/地区或编辑任何现有的默认国家/地区时,只会添加或更新仅适用于该特定商店,且该商店的更改仅对该商店相关查询可见。

例如,样本数据

country table
county_row_id  country_id store_id  status  date_added  is_delete
       1           1          0        1    06/06/2015      0  
       2           2          0        1    06/06/2015      0
       3           3          0        1    06/06/2015      0
       4           4          0        1    06/06/2015      0
       5           3          5        1    07/07/2015      0
       6           1          5        0    07/07/2015      0
       7           4          5        1    07/07/2015      1  

country_description table
country_id  store_id language_id  name    description
      1         0         0       USA     United States of America
      2         0         0       Russia  Russia
      3         0         0       UK      United Kingdom
      4         0         0       India   Bharat
      3         5         0       England United Kingdom
      1         5         0       US      United States of America
      4         5         0       Bharat  India

现在我们想得到store_id = 5的国家/地区列表,其中所有默认值都是store_id = 0加上覆盖为store_id = 5添加或更新的值。

getCountries() : List of Countries in Ascending Order of their Name

SELECT *
FROM country c LEFT JOIN country_description cd
ON (c.country_id = cd.country_id AND c.store_id = cd.store_id)
WHERE (c.store_id = 0 OR c.store_id = 5) AND c.status = 1 AND c.is_delete = 0
ORDER BY cd.name ASC GROUP BY c.store_id

通过上述查询,我​​们得到了结果,但仍未按名称按升序显示。我们通过先排序然后再分组来选择sub_queries来解决这个问题。

现在我们需要限制结果,例如,如果任何国家/地区设置为is_delete为特定商店,结果不应该在结果中获得该行,尽管它具有默认store_id 0的值。我们尝试使用LEFT JOIN和UNION但它并没有在单个查询中解决我们的问题,所以任何人都有任何想法或逻辑以优化的方式解决它。

商店ID 5的预期输出,商店ID 0的默认值:

country_id  store_id  name      status
     3          5     England      0
     1          5     US           1
     2          0     Russia       1

Note : Not showing country_id 4 as it has set is_delete = 1.

我试图找出解决方案,但没有找到哪个可以解决我的问题,所以尝试发布问题以获得一些帮助。

0 个答案:

没有答案