mysql - Mysql join 选择多列最佳实践
问题描述
我正在使用Laravel Query Builder ,并且我的 join 语句运行良好。
User
表列:
name|email|phone|gender
School_Abouts
表列:
courses|boards|contact|location|teachers
目前我做如下选择查询:
$school=User::join('school_abouts', 'users.id', '=', 'school_abouts.school_id')
->where('users.id',$id)
->select('users.name',
'users.email',
'users.phone',
'school_abouts.courses',
'school_abouts.boards',
'school_abouts.contact',
'school_abouts.location',
'school_abouts.teachers')
->first();
要从school_about
表中选择列,我必须多次写入表名。但是有没有办法传递一个列数组呢?我试过这个但失败了:
->select('users.name',
'users.email',
'users.phone',
'school_abouts'.[courses,boards,location,contact,teachers],
)
解决方案
您可以安全地从列中删除表名,因为两个表中没有共同的列名,但正如我所见,您正在尝试从两个表中获取几乎所有列,这可以使用以下方法进行简化*
:
$school = User::join('school_abouts', 'users.id', '=', 'school_abouts.school_id')
->where('users.id', $id)
->select('users.*', 'school_abouts.*')
->first();
但是,如果您想获取某些列并且它们的名称可能会产生歧义,那么必须在列名前加上表名。为了使其更短,您可以使用别名:
$school = User::join('school_abouts AS sa', 'users.id', '=', 'sa.school_id')
->where('users.id', $id)
->select('users.name',
'sa.courses',
'sa.boards',
'sa.contact',
'sa.location')
->first();
推荐阅读
- stack - “窥视”先前放入 yypush_buffer_state 的缓冲区?
- c++ - 拆分字符串输入并查找字符是否有效
- printing - 打印时删除水晶报表中的背景图片
- go - 使用 Golang http 服务器验证 SSL 错误?
- python - t=turtle.Pen() 表示海龟没有属性 Pen
- swift - 在 NSCombobox 中搜索大量数组
- c++ - 如何从 QStyle 获取 QTreeView 的标识宽度
- c++ - 尽管我已经初始化了这个链表,但链表指向 NULL
- java - Java 中的 libvlc 是否与 C 中的 libvlc 一样完整?
- react-redux - 反应表单handleChange没有更新状态