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

jl5161 · April 13, 2018 · Last by jl5161 replied at April 14, 2018 · 3116 hits

表 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 就可以做到去重吧

Reply to clarkyi

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

3 Floor has deleted
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 对吗?

Reply to fan124

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

Reply to 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"

Reply to yakjuly

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

You need to Sign in before reply, if you don't have an account, please Sign up first.