MySQL:根据两个不同表中的几个键选择几行

时间:2017-01-17 11:54:38

标签: php mysql sql key-value

我有两个表格 - user_schedulesuser_schedule_meta,如下所示:

------------------------------------
| id | scheduler_id | status | 
------------------------------------
  1        3          pending 
  2        5          active
  3        6          active

----------------------------------------------
| id | user_schedule_id | meta_key |meta_value
----------------------------------------------
 1         3              course-id    135
 2         3              session-id   15
 3         3              schedule-id  120

我想编写一个查询,以便我能够从两个表中选择满足以下5个条件的每个人:

  1. user_schedule_id = 3
  2. scheduler_id = 6
  3. session_id = 15
  4. course-id = 135
  5. schedule-id = 120
  6. 这是我到目前为止所做的,但它不起作用:

    SELECT user_schedule_meta.`id` FROM user_schedule_meta, user_schedules 
    WHERE user_schedules.`scheduler_id` = 6 
    AND user_schedules.id = user_schedule_meta.`user_schedule_id` 
    AND ( 
    (user_schedule_meta.`meta_key` = 'course-id' AND user_schedule_meta.`meta_value` = 135) 
    OR (user_schedule_meta.`meta_key` = 'session-id' AND user_schedule_meta.`meta_value` = 15) 
    OR (user_schedule_meta.`meta_key` = 'daily-schedule-id' AND user_schedule_meta.`meta_value` = 120) 
    ) 
    GROUP BY user_schedule_meta.`id`
    

    有什么建议我做得不对吗?

2 个答案:

答案 0 :(得分:2)

这是典型的键值存储查找问题。这些比在SQL中看起来更棘手,因为它们需要多个JOIN操作。

您需要一个每user_schedules.id个值为一行的虚拟表,然后您可以对其进行过滤。所以

SELECT u.id, u.scheduler_id
  FROM user_schedules u
  JOIN user_schedule_meta a ON u.id=a.user_schedule_id AND a.meta_key='course-id'
  JOIN user_schedule_meta b ON u.id=b.user_schedule_id AND b.meta_key='session-id'
  JOIN user_schedule_meta c ON u.id=c.user_schedule_id AND c.meta_key='daily-schedule-id'

WHERE a.meta_value = 135  -- value associated with course-id
  AND b.meta_value=15     -- value associated with session-id
  AND c.meta_value=120    -- value associated with daily-schedule-id

另请注意,您可以列出包含此类关联属性的表。这种多次加入键/值表的技巧是一种 pivot 操作。我使用LEFT JOIN,因为它允许结果集显示缺少属性的行。

SELECT u.id, u.scheduler_id, u.status,
       a.meta_value AS course_id,
       b.meta_value AS session_id,
       c.meta_value AS daily_schedule_id
  FROM user_schedules u
  LEFT JOIN user_schedule_meta a ON u.id=a.user_schedule_id AND a.meta_key='course-id'
  LEFT JOIN user_schedule_meta b ON u.id=b.user_schedule_id AND b.meta_key='session-id'
  LEFT JOIN user_schedule_meta c ON u.id=c.user_schedule_id AND c.meta_key='daily-schedule-id'

答案 1 :(得分:0)

试试这是代码

select * from user_schedule_meta where user_schedule_id=3 and 
(meta_key='session-id' AND meta_value=15
or meta_key='daily-schedule-id' AND meta_value=120
or meta_key='course-id' AND meta_value=135
)