多对多关系选择和排序

时间:2012-04-07 18:04:29

标签: php mysql many-to-many

我在两个表之间有多对多的关系:人和收藏。我有三列:

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

为:

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'

我正在使用PHP和MySQL。

如何检索person_id 1和2一起的favorite_id并按person id排序is_main_favorite ='y'的{​​{1}},结果应为:

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')

3 个答案:

答案 0 :(得分:1)

可能类似于此:

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

顺便说一句:您可能希望在数据库中存储1/0而不是y / n,这样您就不需要IF调用

答案 1 :(得分:0)

解决方案

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

如何运作

首先,favorites表连接到persons表两次,每个表都是自己的表(onetwo)。然后,检查两个favorite_id以查看它们是否存在。如果它们都存在,则该行包含在结果集中,并按is_main_favorite的计数排序(如果两个“y”则为2,如果为“y”则为1,或者为0)。

答案 2 :(得分:0)

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