use*_*837 2 mysql sql select join
我有2张桌子:
table_name:user_tracking
包含列:id、bill_no、container_type、origin_id、destination_id
table_name:包含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'
Run Code Online (Sandbox Code Playgroud)
如何将表中的两列origin_id和destination_id同一字段连接id起来sea_ports以获得两个不同的输出?
您需要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'
Run Code Online (Sandbox Code Playgroud)
作为旁注,SQL Injection如果值(s)来自外部,则查询很容易受到攻击。请查看下面的文章,了解如何预防。通过使用,PreparedStatements您可以摆脱在值周围使用单引号。
| 归档时间: |
|
| 查看次数: |
3900 次 |
| 最近记录: |