duanqiao1926 2019-03-31 00:22
浏览 55

为什么我的左连接不能在我的php mysql数据库中工作?

I'm trying to create an sql query that will show me the prices of the services selected by one user within a reservation.

So I want to select the id_service column from my table chosen_services where the id_reservation coresponds to the $_SESSION['idReservation'] and get the price of these services and finaly calculate the total.

here are my 2 tables in mysql : https://ibb.co/NtgLLh7 and https://ibb.co/jkB0Qm6

Here's my query for the moment :

$getPriceOfAllServices = $bdd->prepare(
    'SELECT id_service 
    FROM CHOSEN_SERVICES 
    LEFT JOIN SERVICES ON CHOSEN_SERVICES.id_chosen_service = SERVICES.id_service 
    WHERE id_reservation = ?'
);
$getPriceOfAllServices->execute(array($_SESSION['idReservation']));
$getPriceOfAllServices = $getPriceOfAllServices->fetch();

And I have this error : https://ibb.co/Wc1hLvz

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dsa2c2255888 2019-03-31 00:32
    关注

    SELECT id_service

    Both tables involved in the query have a column called id_service. Since you did not prefix the column name, MySQL cannot reliably tell which of the two you mean, hence it raises the 'ambiguous column name` error.

    Since you are using LEFT JOIN, it is very likely that you want to return the column coming from table CHOSEN_SERVICES (since the other column might be NULL, when the join condition does not match).

    Consider:

    SELECT CHOSEN_SERVICES.id_service 
    FROM CHOSEN_SERVICES 
    LEFT JOIN SERVICES ON CHOSEN_SERVICES.id_chosen_service = SERVICES.id_service 
    WHERE id_reservation = ?
    

    NB: please note that column id_reservation in the WHERE clause is not prefixedeither. While this will not generate the same error (since that column only exists in one of the two tables), it is a good practice to always prefix columns when several tables are involved. Another good habit is to use table aliases.

    Accordingly here is a new version of your query:

    SELECT cs.id_service 
    FROM chosen_services cs
    LEFT JOIN services s ON cs.id_chosen_service = s.id_service 
    WHERE cs.id_reservation = ?
    
    评论

报告相同问题?

悬赏问题

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