简体   繁体   English

MySQL 如果 table1.id = table2.table1_id 查询应该在第一个表中插入第二个表

[英]MySQL Query should insert a second table into the first table if table1.id = table2.table1_id

I have two tables.我有两张桌子。

*brands b*
id, name, img

*models m*
id, name, img, brand_1

I would like to get the following output:我想得到以下 output:

Expeted result / output加速结果 / output

b.id, 
b.name, 
b.img, 
models = m.id, m.name, m.img (where b.id = m.brand_id);

Do I have to do two steps for this?我必须为此做两个步骤吗?

  1. give me all the brands给我所有的品牌
  2. iterate brands and give me all models that are m.brand_id = b.id .迭代品牌并给我所有m.brand_id = b.id的模型。

I hope you understand what I mean.我希望你明白我的意思。 In the PHP Laravel Framework you can get one to many relationships as a collection.在 PHP Laravel 框架中,您可以将一对多关系作为一个集合。 Now my question: Can I solve this with a query?现在我的问题是:我可以通过查询来解决这个问题吗? And is my approach the right one at all?我的方法完全正确吗?

You can laravel always let you show the raw query that the quera builder constructs.您可以 laravel 始终让您显示 quera builder 构造的原始查询。

but basically you are searching for an INNER JOIN但基本上你正在寻找一个INNER JOIN

SELECT
  b.id, 
  b.name, 
  b.img, 
  m.id as models
  , m.name
  , m.img 
FROM models  m INNER JOIN brands ON b.id = m.brand_id;
①如果本文未解决您的问题,请点击查看与本文相关的问题
②如果本文未解决您的问题,请向程序员专用AI小助手提问
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 连接两个表,其中table1.id等于table2.table1_id,但仅显示table1.id中在table2.table1_id中找不到的行 - Join two tables where table1.id equals table2.table1_id, but only display rows from table1.id that cannot be found in table2.table1_id PHP MYSQL JOIN QUERY 2 数据库,其中 table1.id = table2.id,如何将 table2.content 显示为 table1.id - PHP MYSQL JOIN QUERY 2 Databases, Where table1.id = table2.id, How to display table2.content as table1.id MySQL-如果table1.id = table2.id> 1则显示一行 - Mysql - Show one row if table1.id = table2.id > 1 MySQL Select语句where table1.id!= table2.id - MySQL Select statement Where table1.id != table2.id 当第二个表的 id 依赖于第一个表时,使用 php 一次插入两个表 - Insert two table at a time mysql using php when id of second table is depend on first table 在我的MySQL中,使用单词JOIN或使用:table1.id = table2.id有什么区别? - In my MySQL what is the difference between using the word JOIN or using: table1.id=table2.id MySQL使用table1.id REGEXP table2.id为同一组选择不同的行 - MySQL select distinct rows for same group using table1.id REGEXP table2.id 使用JOIN将Identical Id列插入第二张表插入第一张表 - Using JOIN to INSERT INTO second Table with an Identical Id column as the first Table MySql:从另一个表插入表SELECT中,其中first_table ID = another_table.id - MySql: insert into table SELECT from another table where first_table ID =another_table.id 使用第一个表的自动递增的ID更新第二个表 - update second table with the autoincremented id of the first table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM