此查询有望在Mysql中运行:
SELECT category AS category_name, COUNT(id) AS total_books,
(SELECT COUNT(language) FROM books WHERE language = 'lang1' AND category = category_name) AS lang1,
(SELECT COUNT(language) FROM books WHERE language = 'lang2' AND category = category_name) AS lang2,
(SELECT COUNT(language) FROM books WHERE language = 'lang3' AND category = category_name) AS lang3
FROM books GROUP BY category
但是在SQLite中,它引发错误:房间[SQLITE_ERROR] SQL错误或缺少数据库(没有这样的列:category_name)
为什么会这样?对于此查询,SQLite是否需要与Mysql不同的方法?
答案 0 :(得分:2)
MySQL允许使用别名似乎更为宽松。您可以尝试使用更明确的别名来重写查询,如下所示:
SELECT
category AS category_name,
COUNT(id) AS total_books,
(SELECT COUNT(language) FROM books b2
WHERE language = 'lang1' AND b2.category = b1.category) AS lang1,
(SELECT COUNT(language) FROM books b2
WHERE language = 'lang2' AND b2.category = b1.category) AS lang2,
(SELECT COUNT(language) FROM books b2
WHERE language = 'lang3' AND b2.category = b1.category) AS lang3
FROM books b1
GROUP BY category;
但是写一个更好的方法可能是用条件聚合代替相关的子查询:
SELECT
category AS category_name,
COUNT(id) AS total_books,
COUNT(CASE WHEN language = 'lang1' THEN 1 END) AS lang1,
COUNT(CASE WHEN language = 'lang2' THEN 1 END) AS lang2,
COUNT(CASE WHEN language = 'lang3' THEN 1 END) AS lang3
FROM books
GROUP BY category;