mysql - 在 SQL 中设置差异

标签 mysql sql

我有以下查询,它为我提供了可提供标题的商店的 group_concat:

http://sqlfiddle.com/#!9/e52b53/1/0

我当前使用的查询给出了这个:

select 
    title.id, title.name, group_concat(distinct store order by store)
from
    version inner join title on version.title_id=title.id inner join version_price 
    on version_price.version_id=version.id 
group by 
    title_id

id  name    group_concat(distinct store order by store) 
1   Titanic Google,iTunes                               
2   Avatar  iTunes  

我想添加一个额外的列,它可以提供以下(硬编码)商店之间的设置差异:(“iTunes”、“Google”、“Amazon”)。正确的查询将给出:

id  name         group_concat(distinct store order by store)    not_on
1   Titanic      Google,iTunes                                  Amazon
2   Avatar       iTunes                                         Amazon,Google

我该怎么做?

最佳答案

您可以加入包含所有商店的表。我将只在子查询中列出它们,但实际创建这样一个表会更好:

select     title.id, 
           title.name, 
           group_concat(distinct store order by store),
           group_concat(distinct nullif(stores.name, store) order by stores.name)
from       version
inner join title 
        on version.title_id=title.id 
cross join (select 'iTunes' as name union
            select 'Google' union
            select 'Amazon') as stores
left join  version_price 
        on version_price.version_id=version.id
       and version_price.store = stores.name
group by   title.id

SQL fiddle

请注意,现在使用外部联接来联接 version_price 非常重要:

这是因为内部联接会消除stores子查询中的不匹配值。使用左连接不会发生这种情况:相反,对于特定的stores.name,version_price 字段表示为null version_price 中没有匹配项。

因此,在分组发生之前,您实际上拥有更多记录,但这些附加 null 值不会对第一个 group_concat 产生影响。然而,它们,也只有那些,确实对第二个做出了贡献。

改进数据库模型

最好的设计是将商店列在引用表中,并按名称索引。或者更好的是,也为这些商店提供 id,并重新设计 version_price 表以使用 store_id 作为外键,而不是 商店(名称)。

关于mysql - 在 SQL 中设置差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38107420/

相关文章:

mysql - 如何在 SQL Server 2012 中的单个查询中使用 alter table column 和 add constraint

mysql - 如何删除MYSQL中所有表中的单个列

c# - sqlhelper 参数缓存中正在使用什么 "cache"

PHP/MySql 如何将 dateTime 从 STRING 转换为 DATE

MySQL 多重聚合

php - 如何在 MySQL 和 PHP 中使用关系表制作新闻源

mysql - 同步模型将 UNSIGNED BIGINT 修改为 UNSIGNED BIGINT(19)

Java JDBC 如何使用 RETURNING 语句处理更新查询

sql - 有没有办法将 DBCC CheckIdent 的值存储到变量中?

sql - 如何将变量传递给 View 中的子选择