如何在MySQL中进行派生查询

时间:2019-03-02 20:32:29

标签: mysql

我试图进行查询,以使我能够看到每个作者用法语和英语写了多少本书。好吧,我知道我必须对两个派生查询进行处理,但是我不知道如何连接它们。我运行后得到的结果没有意义...

可能有一种更简单的方法,但是尝试了几个小时之后,我仍然无法弄清楚。

SELECT tblBooks.fldAuthor, fldFrench, fldEnglish
FROM tblBooks, (
        SELECT fldAuthor, COUNT(*) AS fldFrench
        FROM tblBooks
        WHERE fldLanguage = 'FR'
        GROUP BY fldAuthor
    ) AS French
Join
    (
        SELECT fldAuthor, COUNT(*) AS fldEnglish
        FROM tblBooks
        WHERE fldLanguage = 'EN'
        GROUP BY fldAuthor
    ) AS English
ON French.fldAuthor = English.fldAuthor;

以下是输出:

enter image description here

我不知道是否可以导入数据库,但这是基础:

CREATE TABLE tblBooks(
    fldAuthor   CHAR(30),
    fldTitle    CHAR(30),
    fldLanguage CHAR(2));


INSERT INTO tblbooks
VALUES('Markus', 'abc', 'EN');

INSERT INTO tblbooks
VALUES('Santa', 'dfs', 'EN');

INSERT INTO tblbooks
VALUES('Santa', 'bcd', 'EN');

INSERT INTO tblbooks
VALUES('Santa', 'fge', 'FR');

1 个答案:

答案 0 :(得分:1)

此示例在SQL Server中完成,但是该概念会将其转换为MySQL。

--create a populated temp table
select *
into #tblBooks
from
(
  values
  ('Book 1', 'Charlie Brown', 'EN'),
  ('Book 2', 'Mickey Mouse', 'EN'),
  ('Livre 3', 'Jacques Clouseau', 'FR'),
  ('Book 4', 'Charlie Brown', 'EN'),
  ('Livre 5', 'Jacques Clouseau', 'FR'),
  ('Book 6', 'Charlie Brown', 'EN'),
  ('Livre 7', 'Pepe le Pew', 'FR'),
  ('Book 8', 'Jacques Clouseau', 'EN'),
  ('Book 9', 'Charlie Brown', 'EN'),
  ('Livre 10', 'Charlie Brown', 'FR')
) d (fldBookName, fldAuthor, fldLanguage);

--look at data in temp table
select * from #tblBooks;

--calculate number of French books and number of English books for each author
select
fldAuthor,
fldFrench = sum(case fldLanguage when 'FR' then 1 else 0 end),
fldEnglish = sum(case fldLanguage when 'EN' then 1 else 0 end)
from #tblBooks
group by
fldAuthor;

这是结果-
#tblBooks的内容:
enter image description here
摘要:
enter image description here

如果MySQL具有IF,也可以用该语句替换CASE语句,以将其缩短一点。

上面的版本是我解决该问题的方法,因为它非常简洁。但是,这是一个使用派生表来实现与上述相同的汇总结果的版本(在SQL Server中也已完成):

select distinct
b.fldAuthor,
fldFrench = isnull(f.fldFrench, 0), --case when f.fldFrench is null then 0 else f.fldFrench end,
fldEnglish = isnull(e.fldEnglish, 0) --case when e.fldEnglish is null then 0 else e.fldEnglish end
from #tblBooks b
left outer join
  (
    select fldAuthor, fldFrench = count(1)
    from #tblBooks
    where fldLanguage = 'FR'
    group by fldAuthor
  ) f on b.fldAuthor = f.fldAuthor
left outer join
  (
    select fldAuthor, fldEnglish = count(1)
    from #tblBooks
    where fldLanguage = 'EN'
    group by fldAuthor
  ) e on b.fldAuthor = e.fldAuthor;

不确定MySQL是否具有ISNULL的等效项,如果不是,则只需替换为CASE语句,如上所示并带有内联注释。这样做的目的是当找不到给定语言的给定作者的书时,显示零而不是NULL。