mysql在两个表中搜索一个值,然后将其合并

6g8kf2rb  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(248)

我有一个问题,管理显示时,搜索两个表中的一个,并显示它与关系表显示。我给一个样品

table "plates"

ID | NAME
----------------
1  | piza
2  | soft drink
3  | ice cream

table "ingredients"

ID | NAME 
-------------------
1  | tomato 
2  | pepperoni
3  | ice 
4  | mint leaf 
5  | lemon 
6  | ice manggo
7  | ice watermelon 

table "plate_ingredient_relations"

ID | PLATE_ID | PLATE_INGREDIENTS 
-----------------------------------
1  |     1    |     1
2  |     1    |     2
3  |     2    |     3
4  |     2    |     4
5  |     2    |     5
6  |     3    |     6
7  |     3    |     7

如果我想搜索“ice”,这里是我的查询

SELECT 'plate' AS type, id, name FROM `plates` WHERE name like '%ice%'
UNION
SELECT 'ingredient', id, name FROM `ingredients` WHERE name like '%ice%'

结果就是这样

type        | id | name 
---------------------------------
plate       |  3 | ice cream
ingredient  |  3 | ice
ingredient  |  6 | ice manggo
ingredient  |  7 | ice watermelon

问题是。从这个结果来看。我可以这样显示结果吗?

soft drink - ice 
ice cream  - ice manggo 
ice cream  - ice watermelon

如果与“板块成分关系”表有关

j5fpnvbx

j5fpnvbx1#

SELECT CONCAT(p.name, " - ", i.name) as plate_ingredient
FROM

plate_ingredient_relations r
    JOIN plates p
        ON r.plate_id = p.id

    JOIN ingredients i
        ON r.plate_ingredients = i.id

WHERE
    p.name like '%ice%'
    OR i.name like '%ice%';
y4ekin9u

y4ekin9u2#

联接表

裁判:https://dev.mysql.com/doc/refman/8.0/en/join.html

SELECT plates.NAME, ingredients.NAME FROM plate_ingredient_relations 
INNER JOIN plates on plate_ingredient_relations.plate_id = plates.id 
INNER JOIN ingredients ON plate_ingredient_relations.plate_ingredients = ingredients.id 
WHERE ingredients.name LIKE '%ice%'

看一下内部连接,比较句子“on”来匹配表。
如果有用就告诉我。

相关问题