0

嗨,我想将我的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 

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

4

2 回答 2

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
于 2013-02-14T14:30:16.180 回答
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

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

于 2013-02-14T14:31:02.293 回答