dongpao1873 2014-05-09 19:16
浏览 69
已采纳

使用连接两次检索数据

I have the following two MySQL queries.

$delivery_id =

    select c.countries_id 
           from orders o
           LEFT JOIN countries c
           ON c.countries_name = o.delivery_country
           where o.orders_id = 1208;

$billing_id =

    select c.countries_id 
           from orders o
           LEFT JOIN countries c
           ON c.countries_name = o.billing_country
           where o.orders_id = 1208;

With the results being put into the variables (PHP) as appropriate. What I would like to know is, is there a way to combine these two queries into one singular query instead of running it twice. (This is using ZenCart's Query Factory ($db->Execute) where the results will be put into a fields array and recalled as such.

Info about the tables: Each order in orders will contain a billing and delivery address with a country name being found in the appropriate field (billing_country and delivery_country). However, not all orders will contain a delivery address. How can I combine these two into one query? I know that I can use a LEFT JOIN of some sort but am not sure on how to write it.

  • 写回答

2条回答 默认 最新

  • doulipi3742 2014-05-09 19:28
    关注

    You can join the countries table two times using different alias names:

    select 
        c1.countries_id AS delivering_id,
        c2.countries_id AS billing_id
    from orders o
    LEFT JOIN countries c1
         ON c1.countries_name = o.delivery_country
    LEFT JOIN countries c2
         ON c2.countries_name = o.billing_country
    where o.orders_id = 1208;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度