【发布时间】:2015-11-06 12:24:59
【问题描述】:
我有一种情况,我需要通过加入table_1、table_2、table_3、table_6来获取数据,下面是代表我需要放在查询下方的所有条件的查询,效果很好并获得完美的数据
查询 1
SELECT table_1.id
AS id1, table_1.deal_id
AS deal_id5, CONVERT_TZ(table_1.due_date, 'UTC', 'EST')
AS sclr20, table_2.deal_name
AS deal_name22 FROM table_1 INNER JOIN table_2 ON (table_1.deal_id
= table_2.deal_id) INNER JOIN table_3 ON (table_1.id = table_3.child_bwic_id) INNER JOIN table_6 ON (table_6.id =
table_3.bwic_id)
WHERE table_6.data_source_id <> 2
AND table_1.status IN (1, 2, 3)
AND DATE(table_1.due_date) = '2015-08-13'
GROUP BY table_1.deal_id, sclr20 ORDER BY sclr20 ASC, id1 ASC;
现在由于某些要求,我需要再添加一张表到条件table_4,并检查table_4 中是否存在记录,然后标记它,因此我编写查询以左连接table_4 为:
查询 2
SELECT table_1.id
AS id1, table_1.deal_id
AS deal_id5, CONVERT_TZ(table_1.due_date, 'UTC', 'EST')
AS sclr20, table_2.deal_name
AS deal_name22, if(table_4.id IS NULL, 'public', 'private')
AS sclr51
FROM child_bwic table_1 INNER JOIN deal table_2 ON (table_1.deal_id
= table_2.deal_id) INNER JOIN bwic_child_association table_3 ON (table_1.id = table_3.child_bwic_id) INNER JOIN bwic table_6 ON
(table_6.id = table_3.bwic_id)
LEFT JOIN bwic_private_group_association table_4 ON table_6.id =
table_4.bwic_id
WHERE table_6.data_source_id <> 2
AND table_1.status IN (1, 2, 3)
AND DATE(table_1.due_date) = '2015-08-13'
GROUP BY table_1.deal_id, sclr20 ORDER BY sclr20 ASC, id1 ASC;
这个也很好用并且给出了正确的结果集
要进一步深入研究结果,我需要将table_4 与table_5 一起加入,这样我就可以将结果限制在特定用户的组中。所以我把查询写成:
查询 3
SELECT
table_1.id
AS id1, table_1.deal_id
AS deal_id5, CONVERT_TZ(table_1.due_date, 'UTC', 'EST')
AS sclr20, table_2.deal_name
AS deal_name22, if(table_4.id IS NULL, 'public', 'private')
AS sclr51 FROM child_bwic table_1 INNER JOIN deal table_2 ON
(table_1.deal_id = table_2.deal_id) INNER JOIN
bwic_child_association table_3 ON (table_1.id = table_3.child_bwic_id)
INNER JOIN bwic table_6 ON (table_6.id = table_3.bwic_id)
LEFT JOIN bwic_private_group_association table_4 ON table_6.id =
table_4.bwic_id JOIN bwic_private_group_user_association table_5 ON
table_4.group_id = table_5.group_id AND table_5.user_id = 1512
WHERE table_6.data_source_id <> 2
AND table_1.status IN (1, 2, 3)
AND DATE(table_1.due_date) = '2015-08-13'
GROUP BY table_1.deal_id, sclr20 ORDER BY sclr20 ASC, id1 ASC;
但如果我在查询 2 中得到的 table_4(公共记录)中不存在记录,则此查询不会返回结果。
我不想将查询 1 的联接结果与table_4 和table_5 的内部联接分开。
任何帮助将不胜感激。
编辑:
还忘了提到我正在使用 Doctrine Query Builder。所以我没有子查询的选项。我已简化此查询以避免显示 Doctrine QB 实现。
【问题讨论】: