Home > other >  Cant fetch 2 values from other table SQL Query,
Cant fetch 2 values from other table SQL Query,

Time:04-05

I'm newbie on SQL, I have 2 simple tables

ip_track

id current_ip_id old_ip_id
1 1 1
2 2 9
3 1 8

And ip

id ip
1 8.8.8.8
2 195.19.97.117
8 8.8.4.4
9 1.2.3.4

AND I want to get current_ip_id and old_ip_id with its ip in SELECT Statement like

id current_ip_id current_ip old_ip_id old_ip
1 1 8.8.8.8 1 8.8.8.8
2 2 195.19.97.117 9 1.2.3.4
3 1 8.8.8.8 8 8.8.4.4

But if ids are different I got duplicates For example, for
SELECT ip_track.id, current_ip_id, ip AS current_ip, old_ip_id, ip AS old_ip FROM ip_track INNER JOIN ip ON current_ip_id = ip.id OR old_ip_id = ip.id

id current_ip_id current_ip old_ip_id old_ip
1 1 8.8.8.8 1 8.8.8.8
2 2 195.19.97.117 9 195.19.97.117
3 2 1.2.3.4 9 1.2.3.4
4 1 8.8.8.8 8 8.8.8.8
5 1 8.8.4.4 8 8.8.4.4

But expect

id current_ip_id current_ip old_ip_id old_ip
1 1 8.8.8.8 1 8.8.8.8
2 2 195.19.97.117 9 1.2.3.4
3 1 8.8.8.8 8 8.8.4.4

How can it be solved?

CodePudding user response:

Join the ip table to the ip_track table twice:

SELECT
    ipt.id,
    ipt.current_ip_id,
    ip1.ip AS current_ip,
    ipt.old_ip_id,
    ip2.ip AS old_ip
FROM ip_track ipt
LEFT JOIN ip ip1
    ON ip1.id = ipt.current_ip_id
LEFT JOIN ip ip2
    ON ip2.id = ipt.old_ip_id
ORDER BY ipt.id;
  • Related