【问题标题】:MySQL join two columns on a single columnMySQL在一个列上连接两列
【发布时间】:2013-01-27 13:11:27
【问题描述】:

我有 2 张桌子:

  1. 表名:user_tracking
    有列:id、bill_no、container_type、origin_id、destination_id

  2. 表名:sea_ports
    有列:id、bill_no、port_name

我想编写一个查询来获取源端口名和目标端口名。

我的查询是:

select a.container_type, 
       b.port_name as origin_port
from user_tracking a 
left join sea_ports b 
on a.bill_no = b.bill_no 
where a.bill_number = '$bill_no'

如何在表sea_ports 的同一字段id 上连接两列origin_iddestination_id 以获得两个不同的输出?

【问题讨论】:

    标签: mysql sql select join


    【解决方案1】:

    您需要加入表sea_ports 两次,这样您才能获得每个起点和终点的port_name。还有一件事,我猜,您需要使用INNER JOIN 而不是LEFT JOIN,因为总会有目的地和起点,对吧? :D

    SELECT  a.ID,
            a.bill_no,
            a.container_type,
            b.port_name AS Origin_name,
            c.port_name AS Destination_name
    FROM    user_tracking a
            INNER JOIN sea_ports b
                ON a.origin_id = b.id
            INNER JOIN sea_ports c
                ON a.destination_id = c.id
    WHERE   a.bill_number = '$bill_no'
    

    作为旁注,如果值 (s) 来自外部,则查询很容易受到 SQL Injection 的攻击。请看下面的文章,了解如何预防。通过使用PreparedStatements,您可以摆脱在值周围使用单引号。

    【讨论】:

    • @JW.. 哦,太棒了...它起作用了。非常感谢..我肯定会通过链接。再次感谢一吨。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    相关资源
    最近更新 更多