2013-02-11 52 views
2

基本上在这个Web应用程序中,我有一个事件模块,用户可以在其中创建,编辑和删除事件也可以上传该事件的照片。其他用户可以通过选择I'm in按钮或仅提及事件Sound's Cool来参与特定事件。 现在有3个表event_photo(用户上传图片将保存在这里),event_inevent_cool,现在我需要一个事件活动饲料,因为我需要将所有3个表组合为photo,incool。所以我需要建议是否创建一个表来列出这些活动,或者我应该结合所有的结果在PHP中。以前我将所有2个结果结合在一张表中,但现在我想尝试一些不同的结果。有表结构。Myspp结合3表

event_photo表

id  photo_url  business_id  event_id   user_id caption added_date 
1   1111    12    2    3  test1  20130209t1 
2   1122    13    3    4  test2  20130209t4 
3   1133    14    2    3  test3  20130209t2 

event_in表

id event_id user_id date_created 
1   2    3  20130209t3 

event_cool

id event_id user_id date_created 
1   2    4  20130209t5 
2   3    3  20130209t6 

现在的饲料会是这样,基于date_created desct6 -> t1

User_3 says cool for Event_3 
User_4 says cool for Event_2 
User_4 added photo for Event_3 
User_3 added photo for Event_2 
User_3 attending Event_2 
User_3 added photo for Event_2 
User_3 added photo for Event_2 

现在的表应该怎么设计,我希望这是很重要的问题,因为这可以解决有关活动feed.Thanks

回答

1

的选择是有你的三个表,并有类似的东西对它们进行查询:

SELECT * 
    FROM 
     (SELECT user_id, 
        event_id, 
        date_added as date_created, 
        'photo' as type 
      FROM event_photo 
      UNION 
      SELECT user_id, 
        event_id, 
        date_created, 
        'event_in' as type 
      FROM event_in 
      UNION 
      SELECT user_id, 
        event_id, 
        date_created, 
        'event_cool' as type 
      FROM event_cool 
     ) s 
    ORDER BY date_created 

要简化你的代码,你可以创建一个视图:

CREATE OR REPLACE VIEW v_ordered_actions AS 
    SELECT * 
    FROM 
     (SELECT user_id, 
        event_id, 
        date_added as date_created, 
        'photo' as type 
      FROM event_photo 
      UNION 
      SELECT user_id, 
        event_id, 
        date_created, 
        'event_in' as type 
      FROM event_in 
      UNION 
      SELECT user_id, 
        event_id, 
        date_created, 
        'event_cool' as type 
      FROM event_cool 
     ) s 
    ORDER BY date_created; 
+0

它是如何工作的。 。? – d3bug3r 2013-02-11 09:46:52

+0

你是什么意思?第一个版本只是一个可以从MySQL客户端或PHP代码执行的查询。第二个必须在MySQL客户端(如PHPMyAdmin)上执行,然后您可以执行如下操作:'SELECT * from v_ordered_actions WHERE ....' – 2013-02-11 09:57:31

+0

yes我得到结果,但结果没有提及结果排是什么?..? event_in,event_cool或添加照片 – d3bug3r 2013-02-11 10:02:58

1

可以使用,当然UNION诸多问题:http://dev.mysql.com/doc/refman/5.1/en/union.html然而,这是相当缓慢。也许最好创建一个表,如活动日志,其中只是存储:

  • ENTITY_TYPE(中/冷/摄)
  • ENTITY_ID(在目标表行的ID)
  • 事项标识
  • USER_ID
  • 日期

并通过此选择。选择该选项时,为每个目标表分别收集所有ID,并从该表中获取必要信息(如有必要),作为索引数组返回。 Foreach活动提供并为其分配正确的数据。

希望这可以帮助你。