简体   繁体   中英

MySQL: for each row on table then get data from other table

I'm having a problem in MySQL. It involves two tables, now the first table queries the TrackingNo then other table queries the details based on the TrackingNo . (See sample image below)

>> Table1

在此处输入图片说明

>> Table2

在此处输入图片说明

As you can see the images above, Table1 returns 77 records then those 77 records has details on Table2 .For example, TrackNo. xxx000001 must get the newest date/time which is 2015-03-09 17:53:14 and same on the other TrackNo.

My problem is what query should I use? I think, this problem works great on SQL Server using WITH CTE but I made some research that WITH Clause is not supported in MySQL .

>> Desired output:

+-----------+----------+---------------------+
|  TrackNo  |  Status  |      Date/Time      |
+===========+==========+=====================+
| xxx000001 | Logged   | 2015-03-09 17:53:14 |
+-----------+----------+---------------------+
| xxx000002 | Prepped  | 2014-08-15 17:19:00 |
+-----------+----------+---------------------+
| xxx000003 | Analyzed | 2014-10-10 11:12:00 |
+-----------+----------+---------------------+

Any suggestions and alternatives is much appreciated!

Thanks in advance!

Try this:

SELECT 
   t2.TrackNo, 
   t2.Status, 
   MAX(t2.DateTime) 
FROM Table1 t1, Table2 t2 
WHERE t1.TrackNo = t2.TrackNo 
GROUP BY t2.TrackNo

In MYSQL we have powerful operations called JOINS. You can use JOIN to get the output from the two tables based on the column that is same on both tables.

For example:

   SELECT 
   table2.TrackNo, table2.Status, MAX(table2.DateTime) 
FROM Table1 table1, Table2 table2
WHERE table1.TrackNo = table2.TrackNo 
GROUP BY table2.TrackNo;

选择* FROM TrackingNo作为t1,其中t1.date =(从TrackingNo选择max(t2.date)作为t2,其中t1.trackNo = t2.trackNo)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM