[英]MySQL: for each row on table then get data from other table
I'm having a problem in MySQL. 我在MySQL中遇到问题。 It involves two tables, now the first table queries the TrackingNo then other table queries the details based on the TrackingNo .
它涉及两个表,现在第一个表查询TrackingNo,然后其他表根据TrackingNo查询详细信息。 (See sample image below)
(请参见下面的示例图片)
>> Table1 >>表1
>> Table2 >>表2
As you can see the images above, Table1 returns 77 records
then those 77 records has details on Table2 .For example, TrackNo. 如上图所示, 表1返回
77 records
然后这些77条记录具有表 2的详细信息。例如TrackNo。 xxx000001
must get the newest date/time which is 2015-03-09 17:53:14
and same on the other TrackNo. xxx000001
必须获得最新的日期/时间 ,即2015-03-09 17:53:14
并且在其他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 . 我认为,此问题在使用
WITH CTE
SQL Server上效果很好,但是我进行了一些研究,发现MySQL不支持WITH Clause
。
>> 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. 在MYSQL中,我们有强大的操作,称为JOINS。 You can use JOIN to get the output from the two tables based on the column that is same on both tables.
您可以使用JOIN根据两个表上相同的列从两个表中获取输出。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.