SQL JOIN查询 - 链接四个表

时间:2013-07-21 11:55:04

标签: mysql sql join multiple-tables

我有SQL显示该活动的所有活动和相对管理员权限(如果有)。

当前SQL代码:

SELECT `activities`.*, `admins`.`admin_role_id`
FROM (`activities`)
LEFT JOIN `admins` ON `admins`.`activity_id`=`activities`.`id` AND admins.member_id=27500
WHERE `activities`.`active` =  1

返回:

  

id |名字|描述|活跃的| admin_role_id(或null)

然后我需要检测它们是否是该活动中的活跃成员。

我有以下SQL代码:

SELECT DISTINCT `products`.`activity_ID` as joinedID
FROM (`transactions_items`)
JOIN `transactions` ON `transactions`.`id` = `transactions_items`.`id`
JOIN `products` ON `products`.`id` = `transactions_items`.`product_id`
JOIN `activities` ON `activities`.`id` = `products`.`activity_ID`
WHERE `transactions`.`member_id` =  27500
AND `activities`.`active` =  1

有没有办法将其合并为一个SQL查询。由于JOIN的复杂性,我无法弄清楚如何使用正确的JOIN查询。

请帮助,谢谢! :)

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT `activities`.*, `admins`.`admin_role_id`
FROM (`activities`)
LEFT JOIN `admins` ON `admins`.`activity_id`=`activities`.`id` AND admins.member_id=27500
    JOIN (`transactions_items`
    JOIN `transactions` ON `transactions`.`id` = `transactions_items`.`id`
    JOIN `products` ON `products`.`id` = `transactions_items`.`product_id`)
ON `activities`.`id`=`products`.`activity_ID`
WHERE `transactions`.`member_id` =  27500
AND `activities`.`active` =  1

答案 1 :(得分:0)

在我看来,像这样的查询会更容易理解,而且(我认为)更贴切地遵守规范......

SELECT c.*
     , d.admin_role_id
  FROM activities c
  LEFT 
  JOIN admins d
    ON d.activity_id = c.id 
   AND d.member_id = 27500
  LEFT
  JOIN products p
    ON p.activity_ID = c.id 
  LEFT
  JOIN transactions_items ti
    ON ti.product_id = p.id
  LEFT
  JOIN transactions t
    ON t.id = ti.id
   AND t.member_id =  27500
 WHERE c.active =  1