SQL statement Join three tables
Вопрос
i have the following statement
SELECT di_id,
di_name,
di_location,
ig_name,
in_latitude,
in_longitude
FROM dam_info
LEFT JOIN instrument_group
ON ig_diid = di_id
LEFT JOIN instruments
ON in_igid = ig_id;
which returned the result as follow
di_id di_name di_location ig_name in_latitude in_longitude
13 Macap "Kluang, Johor" "Standpipe Piezometer" 1.890895 103.266853
13 Macap "Kluang, Johor" "Standpipe Piezometer" 1.888353 103.267067
1 "Timah Tasoh" "Kangar, Perlis" NULL NULL NULL
2 "Padang Saga" "Langkawi, Kedah" NULL NULL NULL
3 "Bukit Kwong" "Pasir Mas, Kelantan" NULL NULL NULL
4 "Bukit Merah" "Kerian, Perak" NULL NULL NULL
5 Gopeng "Gopeng, Perak" NULL NULL NULL
6 Repas "Bentong, Pahang" NULL NULL NULL
7 Batu "Gombak, Selangor" NULL NULL NULL
8 Pontian "Rompin, Pahang" NULL NULL NULL
9 "Anak Endau" "Rompin, Pahang" NULL NULL NULL
10 Labong "Mersing, Johor" NULL NULL NULL
11 Bekok "Batu Pahat, Johor" NULL NULL NULL
12 Sembrong "Batu Pahat, Johor" NULL NULL NULL
14 Perting "Bentong, Pahang" NULL NULL NULL
15 Beris "Sik, Kedah" NULL NULL NULL
as you can see from the result, there are repeated row which i would like to eliminate one of those and if the table
instruments have more rows to return, then I only want one.
What is the correct statement of achieving that?
thanks in advance
Решение
you could also use a group by clause:
SELECT di_id,
di_name,
di_location,
ig_name,
in_latitude,
in_longitude
FROM dam_info
LEFT JOIN instrument_group
ON ig_diid = di_id
LEFT JOIN instruments
ON in_igid = ig_id
GROUP BY di_id;
Другие советы
Looking at your schema it seems to me that it is on purpose that one di_id
contains multiple instruments, i.e. the instruments
table contains multiple records per in_igid
, as the phrase 'instrument_group' suggests.
One meaningful thing you could do is to return the bounding box of your instruments:
SELECT di_id, di_name, di_location, ig_name,
MIN(in_latitude) as min_latitude,
MAX(in_latitude) as max_latitude,
MIN(in_longitude) as min_longitude,
MAX(in_longitude) as max_longitude
FROM dam_info
left join instrument_group on ig_diid = di_id
left join instruments on in_igid = ig_id
GROUP BY di_id, di_name, di_location, ig_name;
Try to add the keyword DISTINCT after the select keyword.
SELECT DISTINCT di_id,
di_name,
di_location,
ig_name,
in_latitude,
in_longitude
FROM dam_info
LEFT JOIN instrument_group
ON ig_diid = di_id
LEFT JOIN instruments
ON in_igid = ig_id;
Не связан с StackOverflow