MySql根据另外两个表的条​​件在一个表中查找数据

编程入门 行业动态 更新时间:2024-10-24 01:54:05
本文介绍了MySql根据另外两个表的条​​件在一个表中查找数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

通过以下查询帮助我: 我有3个具有这种结构的表.

Help me out with this query: I have 3 tables with this structure.

items_to_groups (item_id | group_id)

items_to_groups (item_id | group_id)

item_to_regions (item_id | region_id)

item_to_regions (item_id | region_id)

项目 [一列]

我需要选择 item 表中与 item_to_groups 表中的item_id匹配的每一行,其中 group = x 并且 item_to_regions 表上的item_id匹配,其中 region = y

I need to select every row on the item table that has an item_id match on item_to_groups table WHERE group = x AND has an item_id match on item_to_regions table WHERE region = y

目前,我拥有的代码是一个带有循环和所有内容的可怕子查询.

Currently the code I have is a horrible subquery with loops and all.

有什么更好的方法? 我曾经考虑过JOIN之类的方法,但实际上并不能完全理解如何做到这一点.

What would be a better way of doing this? I've thought about JOIN and such, but can't really get my head around on how to do it.

推荐答案

SELECT bunch_of_columns FROM items i INNER JOIN items_to_groups ig ON i.id=ig.item_id INNER JOIN items_to_regions ir on i.id=ir.item_d WHERE ir.region_id=y AND ig.group_id=x

查看有关MySQL的 JOIN 文档.联接对于关系数据库很重要. 正如您所说的,您很难掌握联接,请查看有关SQL连接的可视解释,作者是Jeff Atwood.也许有帮助.

Have a look at the JOIN documentation on MySQL. Joins are important for relational databases. As you said you have a hard time grasping joins, have a look at A Visual Explanation of SQL Joins by Jeff Atwood. Maybe it helps.

更多推荐

MySql根据另外两个表的条​​件在一个表中查找数据

本文发布于:2023-10-26 09:44:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529790.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   数据   MySql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!