所以,这是我的数据库:
Item
+---------+-------+
| item_id | name |
+---------+-------+
| 1 | item1 |
| 2 | item2 |
| 3 | item3 |
| 4 | item4 |
+---------+-------+
Type
+---------+-------+
| type_id | name |
+---------+-------+
| 1 | type1 |
| 2 | type2 |
| 3 | type3 |
+---------+-------+
Relation
+-----------+-----------+---------+
| a_item_id | b_item_id | type_id |
+-----------+-----------+---------+
| 1 | 2 | 1 |
| 2 | 3 | 1 |
| 1 | 2 | 2 |
| 4 | 1 | 3 |
+-----------+-----------+---------+
我想获得特定项目的关系。
例如SELECT ... WHERE item_id = 1
应该输出:
+-----------+-------------+-----------+-------------+---------+
| a_item_id | a_item_name | b_item_id | b_item_name | type_id |
+-----------+-------------+-----------+-------------+---------+
| 1 | item1 | 2 | item2 | 1 |
| 1 | item1 | 2 | item2 | 2 |
| 4 | item4 | 1 | item1 | 3 |
+-----------+-------------+-----------+-------------+---------+
查询没问题,但如果你知道如何使用medoo(http://medoo.in/api/select),我真的很感激它的转换。
答案 0 :(得分:0)
解决方案比我预期的要容易,查询需要两个relation
表中的外键连接。表别名是必需的,以防止不明确的列名。
SELECT a_item_id, a_item.name AS a_item_name, b_item_id, b_item.name AS b_item_name, type_id
FROM relation
INNER JOIN item a_item ON a_item.item_id = a_item_id
INNER JOIN item b_item ON b_item.item_id = b_item_id
WHERE a_item_id = 1 OR b_item_id = 1
我没有找到使用medoo创建表别名的方法,所以我不得不使用query
方法。