Tuesday 4 September 2018

How to extract data from two tables using the mysql query with certain conditions applied to the second table?

I want to generate a result from a MySql query with below requirement.

Table 1 :
---------------
| nid | type  |
---------------
|  1  | forum |
|  2  | forum |
|  3  | forum |
|  4  | forum |
---------------

Table 2
-----------------------
| nid | cid | created |
-----------------------
| 1   | 32  | 123456  |
| 2   | 65  | 123457  |
| 4   | 67  | 123458  |
| 1   | 61  | 123491  |
| 1   | 78  | 123497  |
| 2   | 23  | 123498  |
| 1   | 12  | 123698  |
| 4   | 54  | 132365  |
| 4   | 81  | 135698  |
| 1   | 30  | 168965  |
-----------------------

Now i require result like below. (Condition : I need the nid from first table, smallest cid for the corresponding nid in second table WHERE type = 'forum')
--------------
| nid | cid  |
--------------
| 1   |  12  |
| 2   |  23  |
| 4   |  67  |
--------------


You can try this
SELECT tbl1.nid,
       min(tbl2.cid) as cid
FROM table1 tbl1
INNER JOIN table2 tbl2 ON tbl1.nid=tbl2.nid
GROUP BY tbl2.nid;

0 comments:

Post a Comment