加入两个表,其中右表包含ID和子ID,没有重复

时间:2015-09-30 21:16:07

标签: mysql

如果我在表A中有以下条目:

| Cart| X_ID| Y_ID|
|-----------------|
|  1  |  1  | NULL|
|  2  |  1  |  1  |
|  3  |  1  |  2  |
|  4  |  2  | NULL|
|  5  |  2  |  2  |

我有表B:

| xid | xstr| yid | ystr|
|-----------------------|
|  1  |Apple|  1  | Seed|
|  1  |Apple|  2  | Stem|
|  2  | Rock|  1  | Red |
|  2  | Rock|  2  | Blue|

我需要什么:

| Cart| X_ID| xstr| Y_ID| ystr|
|-----------------------------|
|  1  |  1  |Apple| NULL| NULL|
|  2  |  1  |Apple|  1  | Seed|
|  3  |  1  |Apple|  2  | Stem|
|  4  |  2  | Rock| NULL| NULL|
|  5  |  2  | Rock|  2  | Blue|

我现在有一些相当不错的东西,但我觉得效率很低。

SELECT DISTINCT
    A.Cart, 
    A.X_ID, 
    ISNULL(B2.xstr, '') AS xstr
    A.Y_ID, 
    ISNULL(B3.ystr, '') AS ystr
FROM
    A
    LEFT OUTER JOIN (SELECT DISTINCT tmp.xid, tmp.xstr FROM B AS tmp) AS B2
        ON A.X_ID = B2.xid
    LEFT OUTER JOIN (SELECT DISTINCT tmp.yid, tmp.ystr FROM B AS tmp) AS B3
        ON A.Y_ID = B2.yid

有更简单的方法吗?我必须为一堆" ID"

执行此操作

我刚刚意识到这并不能解释X依赖于X.理想情况下,我想检查X!= null,y(x)

1 个答案:

答案 0 :(得分:0)

最简单的方法是:

SELECT
  A.Cart,
  A.X_ID,
  COALESCE(X.xstr, '') AS xstr,
  A.Y_ID,
  COALESCE(Y.xstr, '') AS ystr,
  ..
FROM
  A LEFT JOIN B AS X ON A.X_ID = B.xid
  LEFT JOIN B AS Y ON A.Y_ID = B.yid
GROUP BY
  A.Cart,
  A.X_ID,
  A.Y_ID

对于GROUP BY一些字段和同时选择SELECT非聚合列,通常不被认为是一个好习惯,请参阅how MySQL handles group by queries,但在这种情况下它应该完全没问题。

如果可能的话,我建议您使用规范化的数据库结构。