gpt4 book ai didi

MySQL 在单列上连接两列

转载 作者:行者123 更新时间:2023-11-29 01:42:58 25 4
gpt4 key购买 nike

我有 2 个表:

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

  2. 表名:sea_ports
    包含列:id、bill_no、port_name

我想编写一个查询来获取源 port_name 和目标 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 中的 origin_iddestination_id 两列连接到同一字段 id得到两个不同的输出?

最佳答案

您需要加入表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'

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

关于MySQL 在单列上连接两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14547692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com