MySQL查询从多个表返回包含OR的关系

时间:2013-10-15 15:35:41

标签: mysql sql join

我有两个实体,“用户”和“产品”,以及两个表:一个用于存储哪些用户已查看哪些产品,另一个用于存储哪些用户喜欢哪些产品。我想查询一次并返回结果如下图所示:

表“视图”:

Table Views

表“喜欢”:

Table Likes

查询结果:

enter image description here

理想情况下,结果中不应重复user_id,product_id。请注意,如果用户既不查看也不喜欢某个产品,则不应该返回它(即,不应该返回FALSE,FALSE行)。

由于MySQL不支持FULL JOIN,我怀疑应该有一个使用UNION ALL的解决方法。我很欣赏任何想法。

4 个答案:

答案 0 :(得分:4)

你可以尝试一下:

SELECT user_id, product_id, max(`view`) `view`, max(`like`) `like` FROM (
  SELECT user_id, product_id, TRUE `view`, FALSE `like` FROM views
  UNION ALL
  SELECT user_id, product_id, FALSE, TRUE FROM likes
) s
GROUP BY user_id, product_id

顺便说一下,你应该尽量避免使用viewlike作为名称,因为它们是MySQL中的保留字。

请记住,在MySQL中true1以及false0都是同义词。

小提琴here

答案 1 :(得分:2)

SELECT 
    v.User_ID, v.Product_ID, true AS `View`, IF (l.User_ID, true, false) AS `Like` 
FROM views v
LEFT JOIN likes l ON (l.User_ID = v.User_ID AND l.Product_ID = v.Product_ID)
UNION
SELECT 
    l.User_ID, l.Product_ID, IF (v.User_ID, true, false) AS `View`, true AS `Like` 
FROM likes l
LEFT JOIN views v ON (l.User_ID = v.User_ID AND l.Product_ID = v.Product_ID)
ORDER BY User_ID, Product_ID

答案 2 :(得分:1)

还有一种方法:

SELECT user_id, product_id, 
       'TRUE' AS view_result, 
       CASE WHEN l.user_id IS NULL THEN 'FALSE' ELSE 'TRUE' END AS like_result 
FROM views AS v
  NATURAL LEFT JOIN likes AS l
UNION ALL
SELECT user_id, product_id, 
       'FALSE', 'TRUE'
FROM views AS v
  NATURAL RIGHT JOIN likes AS l
WHERE v.user_id IS NULL ; 

经过测试:SQL-Fiddle

答案 3 :(得分:0)

SELECT
    User_ID,
    Product_ID,
    Views.User_ID IS NOT NULL AS View,
    Likes.User_ID IS NOT NULL AS Like
FROM
    Users
    LEFT JOIN Views USING (User_ID)
    LEFT JOIN Likes USING (User_ID)
WHERE
    Views.User_ID IS NOT NULL
    OR Likes.User_ID IS NOT NULL