[英]SQL JOIN: how to do?
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. 给定的值
table_two_id
,我需要的所有记录table_one
中加入了与列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 或像其他建议一样加入2次
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. 这将从table1,table2,table3中选择所有具有匹配行的行。 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:
如果您需要从table_one中选择所有行,然后尝试通过table_map在table_two中找到一些匹配项,请使用以下方法:
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. —来自table_one的所有行。 When no matching row found — you'll get NULLs in corresponding columns.
如果找不到匹配的行,则在相应的列中将为NULL。
USING
means the query will use columns with matching names: USING
表示查询将使用具有匹配名称的列:
USING(table_one_id)
and is equivalent to: 等效于:
ON(table_one.table_one_id = table_map.table_one_id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.