简体   繁体   中英

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:

Expeted result / 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 .

I hope you understand what I mean. In the PHP Laravel Framework you can get one to many relationships as a collection. 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.

but basically you are searching for an 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM