Many-to-many relationship select and order by

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-14 02:46:57

问题


I have a many-to-many relationship between two tables: person and favorites. I have three columns:

person_id         int(8)
favorites_id      int(8)
is_main_favorite  enum('y','n')

as:

person_id | favorite_id | is_main_favorite

2         | 1           |   'y'
2         | 2           |   'n'
3         | 1           |   'n'
3         | 2           |   'n'
1         | 1           |   'y'
1         | 2           |   'y'

I'm using PHP and MySQL.

How I can retrieve person_id that have (favorite_id 1 and 2 together) and order the result by person id that have more is_main_favorite ='y', so the result should be as:

person_id 

1          (because he has favorite_id 1 and 2 and have two is_main_favorite = 'y')
2          (because he has favorite_id 1 and 2 and have one is_main_favorite = 'y')

回答1:


Probably something similar to this:

SELECT
    a.person_id
FROM
    table AS a,
    table AS b
WHERE
    a.person_id = b.person_id AND
    a.favorite_id = 1 AND
    b.favorite_id = 2
ORDER BY
    ( IF( a.is_main_favorite = "y", 1, 0 )
      +
      IF( b.is_main_favorite = "y", 1, 0 ) ) DESC

By the way: You may want to store 1/0 instead of y/n in the database so that you won't need the IF call




回答2:


Solution

SELECT `person_id`
FROM `persons`
LEFT JOIN `favorites` AS `one`
 ON `favorites`.`person_id` = `persons`.`person_id`
LEFT JOIN `favorites` AS `two`
 ON `favorites`.`person_id` = `persons`.`person_id`
WHERE `one`.`favorite_id` = ?
AND `two`.`favorite_id` = ?
ORDER BY (
 IF(`one`.`is_main_favorite` = "y", 1, 0)
 +
 IF(`two`.`is_main_favorite` = "y", 1, 0)
) DESC

How it works

First, the favorites table is joined to the persons table twice, each as it's own table (one and two). Then, both favorite_ids are checked to see if they exist. If they are both present, the row is included in the result set, and sorted by the count of is_main_favorite (2 if two "y", 1 if one "y", or 0).




回答3:


SELECT p.person_id
FROM person AS p, favorites AS f1, favorites AS f2
WHERE p.person_id = f1.person_id AND
      p.person_id = f2.person_id AND
      f1.favorite_id IS NOT NULL AND
      f2.favorite_id IS NOT NULL
ORDER BY
( IF( f1.is_main_favorite = "y", 1, 0 )
  +
  IF( f2.is_main_favorite = "y", 1, 0 ) ) DESC


来源:https://stackoverflow.com/questions/10056960/many-to-many-relationship-select-and-order-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!