我的查询完美无缺:
SELECT
u.id
, u.mobile
, u.name
, (NOW() - u.authenticationTime) AS authenticateTimeDifference
, u.IP
, c.providerid
, c.requestid
, c.status
, u.port
FROM contacts c
LEFT JOIN users u ON u.id =
IF (
c.providerid = 2
, c.requestid
, c.providerid
) WHERE (
c.providerid = 2
AND c.status = 1
)
OR c.requestid = 2
ORDER BY authenticateTimeDifference
现在我只想选择DISTINCT u.name
字段(或唯一身份用户),因此我将u.name
更改为DISTINCT(u.name)
但我收到错误:
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'DISTINCT(u.name) ,
(NOW() - u.authenticationTime) AS au' at line 4
我也尝试添加GROUP BY u.name
,但仍然没有运气。
有人可以告诉我如何通过上述查询选择唯一的姓名/用户吗?
感谢您的帮助
答案 0 :(得分:1)
首先,您需要使用group by
:
SELECT
u.id
, u.mobile
, u.name
, (NOW() - u.authenticationTime) AS authenticateTimeDifference
, u.IP
, c.providerid
, c.requestid
, c.status
, u.port
FROM contacts c
LEFT JOIN users u ON u.id =
IF (
c.providerid = 2
, c.requestid
, c.providerid
) WHERE (
c.providerid = 2
AND c.status = 1
)
OR c.requestid = 2
GROUP BY u.name
ORDER BY authenticateTimeDifference
然后你必须决定如何处理其他值。它们应该显示最低值,最高值,平均值等吗?由于您只想对名称进行分组,因此您必须为group by
以外的字段选择一个。
答案 1 :(得分:0)
据我说Distinct
必须在选择之后发生。所以你的查询应该是这样的: -
SELECT DISTINCT u.id, u.mobile, u.name, (NOW() - u.authenticationTime) AS authenticateTimeDifference
, u.IP, c.providerid, c.requestid, c.status, u.port
FROM contacts c
LEFT JOIN users u ON u.id =
IF (c.providerid = 2, c.requestid, c.providerid)
WHERE (
c.providerid = 2
AND c.status = 1
)
OR c.requestid = 2
ORDER BY authenticateTimeDifference