duanji5116 2013-04-14 05:48
浏览 76
已采纳

SQL JOIN返回3个名为'id'的字段

I have a SQL query using joins with 3 tables. It actually works fine, but all three tables have a field called 'id', so later when I try to access the id field, it only accesses the one from the last field. The SQL query is as follows:

"SELECT * FROM professors AS p 
            JOIN schools_professors AS sp 
            ON p.school_id = sp.id
            JOIN schools AS s ON sp.school_id = s.id  WHERE p.first_name LIKE '%".
                $search."%' OR p.last_name LIKE '%".$search.
                "%' LIMIT 0, 10;"

now then, the schools, professors, and schools_professors, all have the id column. How do I access the id of professors though? That's the only one I care about.

  • 写回答

1条回答 默认 最新

  • doushenjia8514 2013-04-14 05:50
    关注

    You should not be using * in this case but instead manually project the column names and add an ALIAS on it. Example,

    SELECT   ....,
             p.ID AS ProfessorID,
             s.ID AS SchoolID,
    FROM     .....
    

    As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题