根据第一个表列加入第二个表

时间:2013-02-14 14:28:14

标签: mysql

嗨我想加入我的registry_ug表格和第二张基于registry_ug.type的表格....我想避免不必要的加入。

这是我的代码

   SELECT  ug.id , tbl.id FROM registry_ug ug
      JOIN    CASE ug.type 
             WHEN 1   THEN  users 
             WHEN 2   THEN  group_software 
       END
       AS  tbl
       ON 
       ug.id = tbl.id 

     WHERE ug.id = $uid

对我来说似乎没问题但我得到了这个错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CASE ug.type WHEN 1 THEN users WHEN 2 THEN g' at line 2

SELECT ug.id , tbl.id FROM registry_ug ug JOIN CASE ug.type WHEN 1 THEN users WHEN 2 THEN group_software END AS tbl ON ug.id = tbl.id WHERE ug.id = 55 

* 我不想加入所有可能的第二张桌子*

2 个答案:

答案 0 :(得分:1)

你不能这样做。您不能以这种方式使用CASE表达式。试试这个:

SELECT  
  ug.id, 
  COALESCE(u.id, g.id)
FROM registry_ug AS ug
LEFT JOIN users          AS u ON ug.id = u.id AND ug.type = 1
LEFT JOIN group_software AS g ON ug.id = g.id AND ug.type = 2
WHERE ug.id = $uid

答案 1 :(得分:0)

尝试一下,

SELECT  ug.id , 
        CASE WHEN ug.type = 1 
            THEN b.id 
            ELSE c.id
        END newID
FROM    registry_ug ug
        LEFT JOIN   users b
            ON ug.id = b.id 
        LEFT JOIN   group_software c
            ON ug.id = c.id 
WHERE   ug.id = $uid

无法测试,未添加样本数据