Say I have the following tables:
================
table_one
================
- table_one_id (PK)
- field_1
- field_2
================
table_map
================
- table_one_id
- table_two_id
================
table_two
================
- table_two_id (PK)
- field_1
- field_2
Given the value table_two_id
, I need all the records in table_one
joined with the columns in table_two
WHERE table_one->table_one_id = table_map->table_one_id, table_map->table_two_id = table_two->table_two_id.
you can do it with sub query like
select * from table_one where table_one_id in
(select table_one_id from table_map where table_tow_id = my_value)
or with 2 joins like other suggest
SELECT t1.* FROM table_one t1
JOIN table_map t2 ON t1.table_one_id = t2.table_one_id
WHERE t2.table_two_id = X
SELECT t1.field_1 as t1_field1, t2.field_1 as t2_field2 FROM table_one t1, table_map m, table_two t2 WHERE m.table_two_id=123 AND t1.table_one_id=m.table_one_id AND t2.table_two_id=m.table_two_id
Something like that will give you access to the first field in both tables, simply extend to which fields you want
SELECT *
FROM table_one
CROSS JOIN table_map USING(table_one_id)
CROSS JOIN table_two USING(table_two_id);
This will select all rows from table1,table2,table3 that have matching rows. If you need to select ALL rows from table_one and then try to find some matches in table_two through table_map, use this:
SELECT *
FROM table_one
LEFT JOIN table_map USING(table_one_id)
CROSS JOIN table_two USING(table_two_id);
— all rows from table_one. When no matching row found — you'll get NULLs in corresponding columns.
USING
means the query will use columns with matching names:
USING(table_one_id)
and is equivalent to:
ON(table_one.table_one_id = table_map.table_one_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.