-1

我在mysql中有3个表

table 1
date        name   total recieve
2013-05-09  "aa"    20    15
2013-05-09  "bb"    10    17

table 2
name    tree
"bb"     "a1"
"aa"     "a2"

table 3
date          tree      users
2013-05-09   "a1SI"      19
2013-05-09   "a1NO"      24
2013-05-09   "a2SI"      39
2013-05-09   "a2NO"      22

我需要一个带有树表的视图

这是我需要的观点:

date         name   tree   total    recieve    userSI    userNO  
2013-05-09   "aa"   "a2"    20        15        39         22
2013-05-09   "bb"   "a1"    10        17        19         24

我有一半的查询

SELECT t1.`date` , t1.`name` , t2.`tree` , t1.`total` , t1.`recieve`,
FROM  `table1` t1
INNER JOIN  `table2` t2 ON t1.`name` = t2.`name` 
ORDER BY  `t1`.`date` DESC

但我不知道三个表的视图如何,其他问题是树的记录,因为我有树“a1”和“a1Si”和“a2NO”,并且在视图中我需要关联 3 列

4

2 回答 2

10

您应该能够table3在 的t2.tree和左侧的两个字符上使用以下哪些 JOINS t3.tree

SELECT t1.`date` , t1.`name` , t2.`tree` , t1.`total` , t1.`recieve`,
  max(case when right(t3.tree, 2) = 'SI' then t3.users end) usersSI,
  max(case when right(t3.tree, 2) = 'NO' then t3.users end) usersNO
FROM  `table1` t1
INNER JOIN  `table2` t2 
  ON t1.`name` = t2.`name` 
INNER JOIN `table3` t3
  on t2.tree = left(t3.tree, 2)
group by t1.`date` , t1.`name` , t2.`tree` , t1.`total` , t1.`recieve`
ORDER BY  `t1`.`date` DESC;

请参阅SQL Fiddle with Demo

这也可以使用多个 JOIN 来完成table3

SELECT t1.`date` , t1.`name` , t2.`tree` , t1.`total` , t1.`recieve`,
  t3SI.users usersSI,
  t3NO.users usersNO
FROM  `table1` t1
INNER JOIN  `table2` t2 
  ON t1.`name` = t2.`name` 
LEFT JOIN `table3` t3SI
  on t2.tree = left(t3SI.tree, 2)
  and right(t3SI.tree, 2) = 'SI'
LEFT JOIN `table3` t3NO
  on t2.tree = left(t3NO.tree, 2)
  and right(t3NO.tree, 2) = 'NO'
ORDER BY  `t1`.`date` DESC;

请参阅SQL Fiddle with Demo。您会注意到,LEFT JOIN如果不存在与SIor匹配的树,我将最后两个连接更改为使用 a NO,那么您将返回数据。如果您知道您将有匹配的数据,那么您可以使用 INNER JOIN。

如果你有更长的树名,那么你可以在 JOIN 中实现 LIKE 子句:

SELECT t1.`date` , t1.`name` , t2.`tree` , t1.`total` , t1.`recieve`,
  t3SI.users usersSI,
  t3NO.users usersNO
FROM  `table1` t1
INNER JOIN  `table2` t2 
  ON t1.`name` = t2.`name` 
LEFT JOIN `table3` t3SI
  on t3SI.tree like concat(t2.tree, '%')
  and right(t3SI.tree, 2) = 'SI'
LEFT JOIN `table3` t3NO
  on t3NO.tree like concat(t2.tree, '%')
  and right(t3NO.tree, 2) = 'NO'
ORDER BY  `t1`.`date` DESC;

请参阅带有演示的 SQL Fiddle

于 2013-05-21T20:05:48.170 回答
0

尝试与第三个表进行两次内连接,如下所示:

    SELECT t1.'date' , t1.'name' , t2.'tree' , t1.'total' , t1.'recieve',
      t31.users usersSI,
      t32.users usersNO
    FROM  'table1' t1
    INNER JOIN  'table2' t2 
      ON t1.'name' = t2.'name' 
    INNER JOIN 'table3' t31
      on t2.tree = left(t31.tree, 2) AND right(t31.tree, 2) = 'SI'
    INNER JOIN 'table3' t32
      on t2.tree = left(t32.tree, 2) AND right(t32.tree, 2) = 'NO'
    group by t1.'date' , t1.'name' , t2.'tree' , t1.'total' , t1.'recieve'
    ORDER BY  't1'.'date' DESC;
于 2013-05-21T20:28:31.033 回答