Mysql在select语句中添加变量

时间:2014-10-23 03:55:09

标签: mysql select

我有这样的查询

SELECT a.id AS col1, b.id AS col2, b.title AS col3
FROM tbl1 a
INNER JOIN tbl2 b ON a.tbl2_id=b.id

此查询工作正常,现在如果我创建子查询并传递col2的值,就像这样

SELECT a.id AS col1, b.id AS col2, b.title AS col3, (
    SELECT a.name
    FROM tbl1 a
    INNER JOIN tbl2 b ON a.tbl2_id=b.id
    WHERE a.id= [value of col2]
)
FROM tbl1 a INNER JOIN tbl2 b ON a.tbl2_id=b.id

我怎样才能在子查询中传递col2的值?提前致谢

2 个答案:

答案 0 :(得分:3)

如果我只是将您的查询转换为您想要的,那么结果如下:

SELECT 
    a.id AS col1, 
    b.id AS col2, 
    b.title AS col3,
    t.name
FROM 
    tbl1 a 
        JOIN tbl2 b ON a.tbl2_id = b.id
        JOIN (
            SELECT a.id, a.name 
            FROM tbl1 a 
                JOIN tbl2 b ON a.tbl2_id = b.id 
            ) t ON t.id = b.id;

但我很确定你可以简化它。我不清楚为什么你想以这种方式加入它,但可能是因为表名不是真实的。

答案 1 :(得分:1)

此外,您可以使用MySQL User-Defined Variables以避免多次加入并保持代码更具可读性"

SELECT a.id AS col1, @myBCol2Value := b.id AS col2, b.title AS col3, (
  SELECT a.name
  FROM tbl1 a
  INNER JOIN tbl2 b ON a.tbl2_id = b.id
  WHERE a.id = @myBCol2Value
) AS name
FROM tbl1 a
INNER JOIN tbl2 b ON a.tbl2_id = b.id;