Count (*) from different tables on condition - MYSQL

Viewed 62

enter image description here

In above image, I wish to be listed only the PROUDCT_ID and count from both tables whose count is mismatching. In this case my output should only be:

PROUDCT_ID  COUNT  PROUDCT_ID COUNT
1AHO         1     1AHO       2 

Here, am not interested in comparing values and rather count for proudct_id matters.

Excuse am a beginner to SQL.

1 Answers

As long as you want the same information from both tables you can use following

CREATE TABLE TableA (PRoDUKT_ID varchar(10))
INSERT INTO TableA VALUES ("1AHO"),("1ADS"),("1ADS")
CREATE TABLE TableB (ProDUKT_ID varchar(10))
INSERT INTO TableB VALUES ("1AHO"),("1AHO"),("1ADS"),("1ADS")
SELECT a.ProDUKT_ID, CountA, b.ProDUKT_ID,CountB
FROM
(SELECT ProDUKT_ID,COUNT(*) CountA FROM TableA WHERe PRoDUKT_ID = "1AHO") a INNER JOIN
(SELECT ProDUKT_ID,COUNT(*) CountB FROM TableB WHERe PRoDUKT_ID = "1AHO") b USING (ProDUKT_ID)
ProDUKT_ID | CountA | ProDUKT_ID | CountB
:--------- | -----: | :--------- | -----:
1AHO       |      1 | 1AHO       |      2
SELECT a.ProDUKT_ID, CountA, b.ProDUKT_ID,CountB
FROM
(SELECT ProDUKT_ID,COUNT(*) CountA FROM TableA GROUP BY ProDUKT_ID) a INNER JOIN
(SELECT ProDUKT_ID,COUNT(*) CountB FROM TableB GROUP BY ProDUKT_ID) b USING (ProDUKT_ID)
ProDUKT_ID | CountA | ProDUKT_ID | CountB
:--------- | -----: | :--------- | -----:
1ADS       |      2 | 1ADS       |      2
1AHO       |      1 | 1AHO       |      2

db<>fiddle here

Related