PHP mysql Distinct,仅加载1组id
我正在尝试获取与唯一 ID 无关的顺序的数据。所以简单地说,我的查询是
SELECT DISTINCT id1, id2 FROM messages ORDER BY date
如果我有一个包含以下数据的数据库:
id1 | id2 | date
5 | 6 | 1/2/2011
6 | 5 | 1/1/2011
我只需要加载具有最新日期的列,因为 ids 是相同的 2 个人。真的,我必须加载 ids,其中一个 ids 是你的,所以我现在真正的查询是
SELECT DISTINCT userid_1, userid_2
FROM messages
WHERE userid_2=$dbid
OR userid_1=$dbid
ORDER BY date
,我得到的结果为 [6 5] [5 9] [9 5] [5 15] [5 6] [ 5 17]
结果2和3相同,1和5相同。实际上只需要查询 4 个结果。谢谢!
I'm trying to get data where order doesn't matter with unique ids. So simply my query would be
SELECT DISTINCT id1, id2 FROM messages ORDER BY date
If i have a database with the following data:
id1 | id2 | date
5 | 6 | 1/2/2011
6 | 5 | 1/1/2011
I would only need to load the column with the newest date because the ids are the same 2 people. Really i have to load ids where one of the ids is yours so my real query right now is
SELECT DISTINCT userid_1, userid_2
FROM messages
WHERE userid_2=$dbid
OR userid_1=$dbid
ORDER BY date
and i get a result as [6 5] [5 9] [9 5] [5 15] [5 6] [5 17]
Results 2 and 3 are the same and 1 and 5 are the same. Really only 4 results should be queried. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种选择是:
DISTINCT< /code> 会认为它是相同的。
One option is:
DISTINCT
will regard it as same.如果您的目标是获得不同的配对,则可以执行以下操作,使较小的配对始终位于左列,较大的配对始终位于右侧,从而确保不同的工作:
由于配对总是排列好的,因此不需要任何配对功能。
示例
如果我运行此查询:
我得到:
显然使用布尔值具有相同的效果,更易于阅读,并且可能更快,但是如果您只需要交换两个数字以便一侧始终是,则上述算法很方便较小。
我不确定为什么你会收到错误。我直接从 MySQL 命令行运行测试......
If your goal is to get distinct pairings, you could do the following to get the smaller of the pair always in the left column and the larger into the right, thus ensuring that distinct works:
Since the pairs are always arranged, no need for any pairing functions.
Example
If I run this query:
I get:
Obviously using a boolean has the same effect, is easier to read, and probably is faster, but the above algorithm is handy if you just need to swap two numbers so that one side is always the lesser.
I'm not sure why you would have gotten an error. I'm running my tests directly from the MySQL command line....