简体   繁体   English

2个表之间的联接查询

[英]Join query between 2 tables

I have three tables: 我有三个表:

REGISTERS
------------------
id, name, idColony
------------------
1 , some, 3
2 , othe, 6
3 , sann, 3
------------------

EXTRA_COLONIES
------------------
id, idRegister, idColony
------------------
1,   1,   4
2,   1,   5
3,   2,   8
-----------------

COLONIES
------------------
1, some_colony
2, another_colony
...
...

I have a table called eg REGISTER . 我有一个表,例如REGISTER This table will have an idColony (1 idColony is mandatory) from the COLONIES table.But this REGISTERS record/row can have up to 10 extra idColony s. 该表将有一个idColony (1 idColony是强制性)从COLONIES table.But这个REGISTERS记录/行最多可以有10个额外的idColony秒。 That was the reason for me to separate to another table. 这就是我分开另一张桌子的原因。

So the query I am doing is this: 所以我正在做的查询是这样的:

SELECT table1.field,table2.field...
FROM (`REGISTERS`)
JOIN `EXTRA_COLONIES` ON `EXTRA_COLONIES`.`idRegister` = `REGISTERS`.`id`
WHERE (REGISTERS.idColony = '1' or EXTRA_COLONIES.idColony = '1')
GROUP BY `REGISTERS`.`id`
LIMIT 30

The problem with this query is that gets only the records that have EXTRA_COLONIES because of the link JOIN EXTRA_COLONIES ON EXTRA_COLONIES . idRegister = REGISTERS . id 此查询的问题在于,由于链接JOIN EXTRA_COLONIES ON EXTRA_COLONIES . idRegister = REGISTERS . id ,仅获取具有EXTRA_COLONIES的记录JOIN EXTRA_COLONIES ON EXTRA_COLONIES . idRegister = REGISTERS . id JOIN EXTRA_COLONIES ON EXTRA_COLONIES . idRegister = REGISTERS . id JOIN EXTRA_COLONIES ON EXTRA_COLONIES . idRegister = REGISTERS . id . JOIN EXTRA_COLONIES ON EXTRA_COLONIES . idRegister = REGISTERS . id

How can I get all the records, EXTRA_COLONIES or not? 我如何获得所有记录,是否为EXTRA_COLONIES

LEFT JOIN will solve the problem. LEFT JOIN将解决问题。

Irrespective of any matching idRegister in EXTRA_COLONIES , records from REGISTER should be returned 无论idRegisterEXTRA_COLONIES有任何匹配的EXTRA_COLONIES ,都应返回REGISTER记录

More on MySQL JOIN: http://dev.mysql.com/doc/refman/5.0/en/join.html 有关MySQL JOIN的更多信息: http : //dev.mysql.com/doc/refman/5.0/en/join.html

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

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