MySQL query to count rows with mutual relation using JOIN?


For this, use aggregate function COUNT(*). Let us first create a table −

mysql> create table DemoTable1543
   -> (
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (1.36 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1543 values(57,60);
Query OK, 1 row affected (0.52 sec)
mysql> insert into DemoTable1543 values(60,68);
Query OK, 1 row affected (0.38 sec)
mysql> insert into DemoTable1543 values(90,98);
Query OK, 1 row affected (0.36 sec)
mysql> insert into DemoTable1543 values(98,90);
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1543;

This will produce the following output −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     57 |     60 |
|     60 |     68 |
|     90 |     98 |
|     98 |     90 |
+--------+--------+
4 rows in set (0.00 sec)

Here is the query to count rows with mutual relation like the number 90 in both the columns −

mysql> select count(*) from DemoTable1543 tbl1
   -> join DemoTable1543 tbl2
   -> on tbl1.Value2=tbl2.Value1
   -> where tbl1.Value1=90 and tbl2.Value2=90;

This will produce the following output −

+----------+
| count(*) |
+----------+
|        1 |
+----------+
1 row in set (0.00 sec)

Updated on: 12-Dec-2019

522 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements