0

I have two tables:

  • books: [isbn, book_title, publisher, ...]
  • inventory: [isbn, date, num_changed]

I want to return book titles for those which are on stock. I tried a join (query 1) and got 1054 error, then I substituted the reference with the literal value and now I get 1111 error.

query 1:

SELECT `books`.`isbn`, `books`.`book_title`, SUM( `inventory`.`numbers_changed` ) AS `num`
FROM `books`
INNER JOIN `inventory` ON `books`.`isbn` = `inventory`.`isbn`
WHERE `books`.`publisher` LIKE '%pint%'
AND `num` > '0'

query 2:

SELECT `books`.`isbn`, `books`.`book_title`, SUM( `inventory`.`numbers_changed` )
FROM `books`
INNER JOIN `inventory` ON `books`.`isbn` = `inventory`.`isbn`
WHERE `books`.`publisher` LIKE '%print%'
AND SUM( `inventory`.`numbers_changed` ) > '0'

What's the correct query to use?

Edit
Here are the create table queries:

CREATE TABLE IF NOT EXISTS `books` (
  `isbn` varchar(30) CHARACTER SET ascii NOT NULL,
  `book_title` varchar(255) CHARACTER SET utf8 COLLATE utf8_persian_ci NOT NULL,
  `date_published` varchar(10) CHARACTER SET ascii NOT NULL,
  `author` varchar(40) CHARACTER SET utf8 COLLATE utf8_persian_ci NOT NULL,
  `translator` varchar(40) CHARACTER SET utf8 COLLATE utf8_persian_ci DEFAULT NULL,
  `publisher` varchar(50) CHARACTER SET utf8 COLLATE utf8_persian_ci NOT NULL,
  `ganre` varchar(50) CHARACTER SET utf8 COLLATE utf8_persian_ci NOT NULL,
  `price` int(7) unsigned NOT NULL,
  `cover_pic` int(1) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`isbn`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `inventory` (
  `isbn` varchar(30) CHARACTER SET ascii NOT NULL,
  `date` varchar(10) CHARACTER SET ascii NOT NULL,
  `numbers_changed` int(5) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
4

2 回答 2

1

1054 错误与引用不存在的列有关。实际的错误消息将有助于了解导致问题的原因。

1111 错误是因为您尝试在 WHERE 子句中使用聚合函数(在本例中为 SUM):

WHERE ...
  AND SUM( `inventory`.`numbers_changed` ) > '0'  
      ^
      |__ see this?

...在子查询之外。SQL 语句是从下到上检查的,所以我希望删除 WHERE 子句中的 SUM 将表明 1054 错误仍未解决。

于 2010-09-21T01:58:38.673 回答
1

使用第二个 where 参数

WHERE `books`.`publisher` LIKE '%print%' 
HAVING ( COUNT(`inventory`.`numbers_changed`)  > '0')

代替

WHERE `books`.`publisher` LIKE '%print%'
AND SUM( `inventory`.`numbers_changed` ) > '0'
于 2011-12-19T12:05:26.247 回答