【问题标题】:How do you select all rows which match one individual row in either of a thousand columns?您如何选择与一千列中的任何一列中的一个单独行匹配的所有行?
【发布时间】:2011-11-24 12:39:34
【问题描述】:

例如,我的性格匹配数据库有 1000 列,类型标题如:

autoid | movie_genre_comedy | movie_genre_action | movie_genre_horror | more genres --> 
23432  | 1                  | 0                  | 1                  | 0
3241   | 0                  | 1                  | 1                  | 0
64323  | 0                  | 1                  | 0                  | 0

如何将每一行与 autoid 23432 的行匹配,以便生成下表:

autoid | movie_genre_comedy | movie_genre_action | movie_genre_horror | more genres --> 
23432  | 1                  | 0                  | 1                  | 0
3241   | 0                  | 1                  | 1                  | 

请注意,autoid 为 64323 的行不存在,因为它与所选的 autoid 为 23432 的行没有任何相似的列。

最简单的方法是:

SELECT *
from genretable
WHERE movie_genre_comedy = 1 
OR movie_genre_horror = 1 
OR ........... and so on for up to 1000 parameters. 

【问题讨论】:

  • 我会说一个有 1000 列的表表明设计不佳。
  • 我建议遍历列,如this question
  • "genre_preferences" 需要是一个单独的表。 “Person_id”+“preference”(喜剧、动作、恐怖等)可能是新表中的行。忽必烈是对的——一张有 1000 列的表格确实设计得很糟糕。改变设计,查询变得简单。
  • Pyjammez:你的数据库有一些设计问题。所有movie_genre_AAA 列应该是值而不是列:Movie(MovieID-PK, other columns), Genre(GenreID-PK,Name={comedy, action, etc.}, ... other columns), MovieGenre(MovieID-FK ,GenreID-FK, PK(MovieID+GenreID))。

标签: mysql


【解决方案1】:

您在问题中提到的代码确实是使用当前表结构做您想做的事情的唯一方法。答案是创建两个新表来将用户映射到个性特征,如下所示:

create table `personality_trait_values`
(
     `id` smallint auto_increment primary key
    ,`value` varchar(20) not null unique
);

create table `personality_traits`
(
     `user_id` int not null references `users` (`autoid`)
    ,`personality_trait_id` int not null references `personality_trait_values` (`id`)
    ,unique (`user_id`,`personality_trait_id`)
);

这样,您可以删除描述用户是否具有个性特征的 1000 列,并且您的查询变得更加紧凑:

select u.`autoid`
    from `personality_traits` pt1
        join `personality_traits` pt2
            on pt1.`personality_trait_id` = pt2.`personality_trait_id`
            and pt1.`user_id` != pt2.`user_id`
    where pt1.`user_id` = `v_user_id_to_compare_to`

其中 v_user_id_to_compare_to 是您之前在存储过程中设置的变量(在您的问题中为 23432)。

转换您现在拥有的表结构会有点乏味,但非常值得,并且可以通过明智地使用复制/粘贴来减轻很多乏味。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    相关资源
    最近更新 更多