For example, I have two tables:
CREATE TABLE `augus1dl_ecom`.`test`
(
`id` INT NOT NULL AUTO_INCREMENT,
`cn_no` VARCHAR(10) NOT NULL,
`amt` DECIMAL(8,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE = MyISAM;
CREATE TABLE `augus1dl_ecom`.`test2`
(
`id` INT NOT NULL AUTO_INCREMENT,
`docket_id` VARCHAR(25) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
`cn_id` INT NOT NULL,
PRIMARY KEY (`id`)
) ENGINE = MyISAM;
INSERT INTO `augus1dl_ecom`.`test` (`id`, `cn_no`, `amt`)
VALUES (NULL, 'A', '100'), (NULL, 'B', '200');
INSERT INTO `augus1dl_ecom`.`test2` (`id`, `docket_id`, `cn_id`)
VALUES (NULL, 'DK1', '1'), (NULL, 'DK2', '2'), (NULL, 'DK3', '1') ;
In the test
table the cn_no
is unique. But in test2
table, a single cn_no
(refers to cn_id
) could be inserted more than once.
I mean test.id = test2.cn_id
.
Now I run the following query:
SELECT a.*
FROM test2 a, test b
WHERE b.id = a.cn_id AND b.cn_no = 'A'
It runs successfully. But I don't need data, I need the number of rows/entries. So I run the following query to retrieve number of rows (count) from test
, depending condition which is in test2
:
SELECT count(a.*)
FROM test2 a, test b
WHERE b.id = a.cn_id AND b.cn_no = 'A';
But the query fails with an error. This question was suggested as duplicate of SQL: Combine Select count(*) from multiple tables but it is not. Here I want count(*)
depending on the data which is available in another table. How can I do this correctly?