简体   繁体   English

SQL查询以从多个表中获取结果

[英]SQL Query to get result form multiple tables

I have many to many relationship between two of my tables t1 and t2. 我的两个表t1和t2之间有许多关系。 I am trying to get results from t1 that belongs to a t2, I can with a simple join, but I also want to get all the t2 records that have the relationship to that t1 row. 我试图从属于t2的t1中获得结果,我可以通过简单的联接来获取结果,但我也想获取与该t1行具有关系的所有t2记录。

I'll translate the result i am looking for to json for better understanding: 我会将想要的结果转换为json,以更好地理解:

[
    {
        "name": "t1.1",
        "t2s": [
            {
                "name": "t2.1"
            },
            {
                "name": "t2.2"
            }
        ]
    },
    {
        "name": "t1.2",
        "t2s": [
            {
                "name": "t2.1"
            },
            {
                "name": "t2.3"
            }
        ]
    }
]

UPDATE: this is my current query, which return me data for the relationship, but I am also looking to get all the t2 records that have relationship with t1. 更新:这是我当前的查询,它向我返回关系的数据,但我也希望获得与t1有关系的所有t2记录。

select t1.name,t2.name 
from t1 
join t1_t2 as t1t2 
  on t1t2.id=t1.id 
where t1t2.id = '10'

数据库结构

I hope I understand the goal is here. 我希望我明白目标就在这里。 If you are trying to pull t1.name and t2.name for some t1_t2 row, the following query will do it: 如果您尝试为某个t1_t2行提取t1.namet2.name ,则以下查询将执行此操作:

SELECT t1.name, t2.name
FROM t1_t2
JOIN t1
  on t1_t2.t1_id = t1.id
JOIN t2
  on t1_t2.t2_id = t2.id
WHERE t1_t2.id = 10

Here I simply join t1 , where the ids are equal, than do the same for t2 . 在这里,我只是加入id相等的t1 ,而不是加入t2 If that is all you need, it is pretty straightforward. 如果这就是您所需要的,那就非常简单了。

If on the other hand, you want all t2.name associated with a t1 , you just need to change the WHERE : 另一方面,如果您希望所有与t1相关联的t2.name ,只需更改WHERE

WHERE t1.id = 10

This will get you all the rows that have an association with the t1 row. 这将使您获得与t1行相关联的所有行。

Might I suggest a different, simpler table structure: 我可能会建议使用其他更简单的表结构:

t1:
  id
  t1_t2_id
  name
t2:
  id
  t1_t2_id
  name
t1_t2:
  id

See, here I make the two tables point to the many-to-many table. 看,这里我使两个表指向多对多表。 Then you could just skip the t1_t2 table completely and say: 然后,您可以完全跳过t1_t2表,然后说:

SELECT t2.name FROM t2
JOIN t1
ON t1.t1_t2_id = t2.t1_t2_id
WHERE t1.id = 10

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

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