[英]What is the correct SQL statement for has-many-through joins on multiple classes with single table inheritance
I have two tables, Places and Users 我有两个表,地方和用户
-- Places Table: --
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| type | varchar(15) | NO | | NULL | |
| parent_id | int(11) | YES | MUL | NULL | |
+------------+--------------+------+-----+---------+----------------+
-- Users Table: --
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| city_id | int(11) | YES | MUL | NULL | |
+------------+--------------+------+-----+---------+----------------+
I have three models that all use the Places table and all are subclasses of the Place model. 我有三个都使用Places表的模型,它们都是Place模型的子类。 The places.type column holds the class name of the subclass so I know which model it belongs to.
Places.type列包含子类的类名,因此我知道它属于哪个模型。
Country, State, City. 国家,州,城市。
So, the inheritence structure is as follows: 因此,继承结构如下:
Country < Place State < Place City < Place 国家<地点国家<地点城市<地点
The relationships are as follows: 关系如下:
Country has many States State has many Cities City has many Users 国家有很多州州有很多城市市有很多用户
I want to return all Users within a given Country by joining through the state and city but I can't get the SQL query to work for it. 我想通过加入州和城市来返回给定国家/地区内的所有用户,但是我无法使用SQL查询。
Any SQL gurus out there who can point me in the right direction? 有任何SQL专家可以指出正确的方向吗?
How about this? 这个怎么样? You'll need the id of the country.
您需要输入国家/地区的ID。
SELECT st.name,
city.name,
u.name
FROM users u,
places city,
places st
WHERE u.city_id = city.id
AND city.type = 'city'
AND st.type = 'state'
AND st.id = city.parent_id
AND st.parent_id = @country_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.