[英]MySQL substring to self join
I'm defining the relationship between the two tables using a join table.我正在使用连接表定义两个表之间的关系。 I want to arrange them in the order of many overlapping things.
我想按许多重叠事物的顺序排列它们。 Currently, we are using subquery, is there a way to get the same result using join?
目前,我们正在使用子查询,有没有办法使用连接获得相同的结果?
People FoodTable PeopleFood
ID | NAME ID | Food ID | PeopleId | FoodId
1 BOB 1 Hamberger 1 1 1
2 JOHN 2 Pizza 2 1 2
3 KATY 3 Chicken 3 1 3
4 MILLER 4 Salad 4 2 1
5 AMANDA 5 Sushi 5 2 2
6 2 3
7 3 2
8 3 3
9 4 3
10 4 5
11 5 5
When the table is defined in this way, I want to arrange food tastes similar to Bob's.当以这种方式定义表时,我想安排类似于 Bob 的食物口味。 I'm doing it like this now.
我现在正在这样做。
SELECT people_id, COUNT(people_id) as count
FROM peopleFood
WHERE food_id IN
(SELECT food_id FROM peopleFood
WHERE people_id = 1)
AND people_id != 1
GROUP BY people_id
ORDER BY count DESC;
-- Result -------------
People_id | count
2 3
3 2
4 1
Is there a better way to change this method or use join?有没有更好的方法来改变这种方法或使用加入? Thank you!!!
谢谢!!!
Inner join:内部联接:
SELECT p.People_id, COUNT(p.People_id) as count FROM PeopleTable p
INNER JOIN FoodTable f
ON(p.People_id = f.FoodId)
WHERE people = 1
GROUP BY p.people_id
ORDER BY count DESC;
If it helps, please mark it as an accepted answer!如果有帮助,请将其标记为已接受的答案!
You have been inconsistent in your use of the table and column names -您对表名和列名的使用不一致 -
Tables - PeopleFood
in your sample data but you reference peopleFood
in your query.表 - 示例数据中的
PeopleFood
,但您在查询中引用peopleFood
。
Columns - PeopleId
and FoodId
in your sample data but you reference people_id
and food_id
in your query.列 - 示例数据中的
PeopleId
和FoodId
,但您在查询中引用people_id
和food_id
。
Choose a naming convention and stick to it.选择一个命名约定并坚持下去。 Everyone has there own preference but the important thing is to be consistent.
每个人都有自己的偏好,但重要的是要保持一致。
The equivalent query with INNER JOIN instead of your sub-query is -使用 INNER JOIN 而不是您的子查询的等效查询是 -
SELECT
`pf2`.`people_id`,
COUNT(`pf2`.`food_id`) as `count`
FROM `PeopleFood` `pf1`
INNER JOIN `PeopleFood` `pf2`
ON `pf2`.`people_id` <> `pf1`.`people_id`
AND `pf2`.`food_id` = `pf1`.`food_id`
WHERE `pf1`.`people_id` = 1
GROUP BY `pf2`.`people_id`
ORDER BY `count` DESC;
The performance difference between the two queries is unlikely to be noticeable and it might be argued that the intent is clearer in your version with the sub-query.两个查询之间的性能差异不太可能很明显,并且可能会认为在您的版本中使用子查询的意图更清晰。
The surrogate key ID
on your PeopleFood
table should be dropped in favour of the compound “natural” primary key on people_id
and food_id
.应删除
PeopleFood
表上的代理键ID
,取而代之的是people_id
和food_id
上的复合“自然”主键。
The Cost of Useless Surrogate Keys in Relationship Tables 关系表中无用代理键的成本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.