简体   繁体   中英

SQL Query to get result form multiple tables

I have many to many relationship between two of my tables t1 and 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.

I'll translate the result i am looking for to json for better understanding:

[
    {
        "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.

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:

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 . 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 :

WHERE t1.id = 10

This will get you all the rows that have an association with the t1 row.

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:

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

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