1

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

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具有(favorite_id1 和 2 一起)并通过person id具有更多排序结果is_main_favorite ='y',因此结果应为:

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

3 回答 3

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 调用

于 2012-04-07T18:10:16.633 回答
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
于 2012-04-07T18:26:43.033 回答
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检查两个 s 以查看它们是否存在。如果它们都存在,则该行包含在结果集中,并按is_main_favorite(如果有两个“y”,则为 2,如果有一个“y”,则为 1,或 0)的计数排序。

于 2012-04-07T18:09:16.650 回答