【问题标题】:query to show both joins查询以显示两个连接
【发布时间】:2016-04-28 18:36:50
【问题描述】:

我正在尝试构建查询以输出 CommentsComment_DateUsernameFirst_Name,具体取决于表行中是否存在 UserIDStaffID

我可以只使用UserIDStaffID,但是当我添加两个连接时,它什么也不显示。

所以我需要再次输出CommentsComment_DateUsernameFirst_Name。 任何帮助表示赞赏。

我的查询

 select('Report_Comments.Comments, Report_Comments.Comment_Date, Login.Username, staff.First_Name')
        ->from('Report_Comments')
        ->join('Login staff', 'Report_Comments.UserID = Login.LoginID')
        ->join('staff', 'Report_Comments.UserID_Staff = staff.StaffID');

【问题讨论】:

    标签: mysql sql codeigniter join


    【解决方案1】:

    Report_Comments加入Loginstaff开启Report_Comments.UserID=
    Login.LoginID, Report_Comments.UserID_Staff

    上面缺少join 关键字。如果您希望 join 表,所有这些表都必须是 joined 并带有显式条件。

    更正为:

    SELECT `Report_Comments`.`Comments`, `Report_Comments`.`Comment_Date`, `Login`.`Username`, `staff`.`First_Name`
    FROM `Report_Comments`
    JOIN `Login` ON `Report_Comments`.`UserID` = `Login`.`LoginID
    JOIN `staff` ON `Report_Comments`.`UserID_Staff = `staff`.`StaffID` 
    WHERE `ReportID` = '53'
    

    【讨论】:

    • 很好,感谢您的快速回复。我读了这个,试试看,让你知道 +1 反勾号
    • 连接条件的反引号不匹配。
    • 不工作,但要再试一次。当我让它工作不正常时接受
    【解决方案2】:

    您可以从documentation(搜索“join”)中发现,对join() 的调用有两个必需的参数。第一个是jointable,第二个是joincondition。显然,您将两个表和两个连接条件压缩到它的参数中,这就是 CodeIgniter 生成的查询有错误的原因。

    您的代码应为:

    select('Report_Comments.Comments, Report_Comments.Comment_Date, Login.Username,
        staff.First_Name')
    ->from('Report_Comments')
    ->join('Login', 'Report_Comments.UserID = Login.LoginID')
    ->join('staff', 'Report_Comments.UserID_Staff = staff.StaffID')
    ->where('reportID', '53');
    

    【讨论】:

    • 嗯,虽然这种方式无法获取数据,但如果我只有一个连接,它可以工作,但两者都无法检索数据。但它似乎是正确的。我有戏。
    • 如果我删除任何一个联接,它就可以工作,但它们不能一起工作
    猜你喜欢
    • 2014-12-09
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 2020-03-25
    相关资源
    最近更新 更多