douhui9192 2014-11-22 19:18
浏览 14
已采纳

自联接条件在PHP中失败但在mysql中有效

I have this strange situation and not sure of what is wrong. I have a simple self join to find matches based on some conditions. I have this query running fine in mysql but when I call it through PHP, it doesn't return any values.

select * from Requests p inner join Requests c on c.ID<>p.ID
where usr_ID<>4
and p.c_ID = c.c_ID

This works fine but not the below one.

DB::table('Requests as parent')
  ->join('Requests as child', 'parent.ID', '<>', 'child.ID')
  ->where('parent.usr_ID', '<>', 4)
  **->where('parent.c_ID', '=', 'child.c_ID')**
  ->get();

In the above query, if I remove the second where condition(c_ID), it returns correct values. For all rows, this has a value of 1. If I replace child.c_ID or parent.c_ID by 1, it works again. I have tried with other columns as well and found the same issue.

Any pointers?

  • 写回答

1条回答 默认 最新

  • dosgy00204 2014-11-22 19:25
    关注

    What the query builder makes out of your second where condition is:

    WHERE parent.c_ID = 'child.c_ID'
    

    So instead of a "normal" where() use whereRaw(), which takes your input and injects it right into the final SQL query

    ->whereRaw('parent.c_ID = child.c_ID')
    

    Alternatively you could also use DB::raw() on the third argument

    ->where('parent.c_ID', '=', DB::raw('child.c_ID'))
    

    Both are essentially the same so use whichever you like more.

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

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)