我的MySQL内连接有问题。我的INNER JOIN
没有给我我想要的结果。我的 Table1 只包含TrackNo
Table2 包含每trackNo
Table1 的详细信息。
>>表格结构:
>> SQL代码:
SELECT tr.trackNo AS 'TrackNo',
trD.Status,
MAX(trD.DatePosted) AS `Date/Time`
FROM Tracking AS tr
INNER JOIN TrackingDetails AS trD
ON tr.trackNo = trD.trackNo
WHERE tr.ClientID='client01'
AND trD.trackNo IN ('xx000001','xx000002','xx000003')
AND trD.DatePosted IS NOT NULL
AND trD.Status IN (
'Received',
'Logged',
'Prepped',
'Analyzed',
'Reviewed',
'Final Report',
'Invoiced')
GROUP BY tr.trackNo
ORDER BY tr.trackNo ASC
以上是上面的结果查询:
正如您所看到的,上面的查询结果图片是正确的,但Status
列除外。我的SQL
查询出了什么问题?我错过了什么?
>>期望的输出:
+----------+----------+---------------------+
| TrackNo | Status | Date/Time |
+==========+==========+=====================+
| xx000001 | Logged | 2015-03-09 17:53:14 |
+----------+----------+---------------------+
| xx000002 | Prepped | 2014-08-15 17:19:00 |
+----------+----------+---------------------+
| xx000003 | Analyzed | 2014-10-10 11:12:00 |
+----------+----------+---------------------+
提前致谢!
答案 0 :(得分:1)
这应该会给你正确的结果:
select * from TrackingDetails as a join (
SELECT tr.trackNo AS 'TrackNo',
MAX(trD.DatePosted) AS 'Date_Time'
FROM Tracking AS tr
INNER JOIN TrackingDetails AS trD
ON tr.trackNo = trD.trackNo
WHERE tr.ClientID='client01'
AND trD.trackNo IN ('xx000001','xx000002','xx000003')
AND trD.DatePosted IS NOT NULL
AND trD.Status IN (
'Received',
'Logged',
'Prepped',
'Analyzed',
'Reviewed',
'Final Report',
'Invoiced')
GROUP BY tr.trackNo
ORDER BY tr.trackNo ASC
) as x on x.TrackNo = a.trackNo and a.DatePosted = x.'Date_Time'
如果在mysql中使用group by,则不会指定从不在聚合函数或group by语句中的列获取的值。在大多数其他DBMS中,不允许选择此类列。