如何生成两列不会重复数据的列

时间:2015-04-07 07:02:01

标签: mysql sql

我可以问一些帮助,我怎样才能生成这个lat,lng?

我尝试了这段代码,但它不断重复lat,lng值

SELECT h.*, d.* from
  stdtbl h 
  inner 
     join (
        select std_dtl_id,lat,lng, count(*) total 
       from stdtbl_detail group by std_dtl_id
     ) d

  on h.id = d.std_dtl_id
   inner join stdtbl_detail dt on h.id = dt.std_dtl_id
  where
  h.loginid = '1' AND  h.stdid='013777'

我该如何输出

id          stdid                 loginid                 std_dtl_id         lat                       lng                      total

372         013777                 1                      372                51.507407                 -0.127753                   4

372         013777                 1                      372                51.507384                 -0.127636                    4             

372         013777                 1                      372                51.507332                -0.127839                     4

372         013777                 1                      372                51.507304                 -0.127703                    4


373         013777                 1                      373               40.764442                  -73.923469                   4

373         013777                 1                      373               40.764416                   -73.923329                 4

373         013777                 1                      373               40.764346                   -73.923557                 4

373         013777                 1                      373                40.764299                   -73.923432                 4

这是演示http://sqlfiddle.com/#!9/d6a86/8

提前谢谢。

2 个答案:

答案 0 :(得分:2)

这应该按照你的要求行事:

  select h.*, d.*, f.total 
    from stdtbl h
      inner join stdtbl_detail d   
        on h.id = d.std_dtl_id
      inner join 
        (select std_dtl_id, count(*) total from stdtbl_detail group by std_dtl_id) f
          on f.std_dtl_id = h.id

我已经更新了你的小提琴:http://sqlfiddle.com/#!9/d6a86/25

答案 1 :(得分:1)

通过分析,这很容易。没有,它仍然不是非常困难。首先,只需连接两个表即可获得大部分所需的输出。

SELECT  s.id, s.stdid, s.loginid, d.lat, d.lng
from    stdtbl s
join    stdtbl_detail d
    on  d.std_dtl_id = s.id
where   s.loginid = '1'
    AND s.stdid   = '013777';

这样可以在最后得到你想要的total字段。为此,只需生成一个每行一行的结果并加入到:

SELECT  s.id, s.stdid, s.loginid, d.lat, d.lng, a.total
from    stdtbl s
join    stdtbl_detail d
    on  d.std_dtl_id = s.id
join(
    select  std_dtl_id, count(*) total 
    from    stdtbl_detail
    group by std_dtl_id
) a
    on  a.std_dtl_id = d.std_dtl_id
where   s.loginid = '1'
    AND s.stdid   = '013777';

http://sqlfiddle.com/#!9/d6a86/31/0