Rails Rails 查询数据库,去重求救

jl5161 · 2018年04月13日 · 最后由 jl5161 回复于 2018年04月14日 · 3114 次阅读

表 T

from to
a b
a b
c d
b a
c a

我想要的结果是 查询条件 from = a 或者 to = a 下不重复的数据 并去重 若 from = a,to = xx 或者 from = xx,to = a 只算一条的话 请问如何去重

T.where(from: a).or(T.where(to: a)).select(:from, :to).distinct

补充:因为我要的是 xx 哪个数据 目前对取出的数据通过 array.uniq 去重 但这样效率很低吧

有自增长主键的表的话 sql 就可以做到去重吧

clarkyi 回复

不管主键是什么 因为我的目标数据是 from 或者 to 对应的另一条数据

3 楼 已删除
SELECT IF(STRCMP(`from`, "a") = 0, `to`, `from`) AS another
FROM `table` WHERE `table`.`from` = "a" OR `table`.`to` = "a" GROUP BY another;

这样?

从给的例子来说,最后要得到 a,b 和 c,a 对吗?

fan124 回复

是的 4 楼给的 sql 我还没验证

martin91 回复

除了 sql 支持 rails 写法嘛?谢谢

@jl5161 4 楼的逻辑可以

查询条件 from = a 下不重复的数据 T.where("from=?", "a").group("to").having("count(*) = 1").pluck("to")

若 from = a,to = xx 或者 from = xx,to = a 只算一条的话 T.where("not exist (select * from T t2 where t2.from = t.to and t2.to = t.from) ").group("from, to").having("count(*) = 1").pluck "from, to"

yakjuly 回复

对于 sql 新手 看的头晕 谢谢啊

需要 登录 后方可回复, 如果你还没有账号请 注册新账号