MySql从id获取两个值

时间:2013-03-13 18:01:30

标签: php mysql

我在下面有这个SQL查询,请注意从receiver

返回id的字段table_1

我的问题是如何在FirstName点找到接收器LastNamereceiver

SELECT DISTINCT
    FirstName, 
    LastName, 
    table_2.status, 
    (select FirstName, LastName from table_1 where table_1.id = table_2.receiver) as receiver 
FROM table_1
INNER JOIN 
    table_2 on table_1.key_2 = CONCAT('OFFLINE-', table_2.id)
ORDER BY FirstName, LastName

我在SQL中添加了一个子查询,但这给了我一个语法错误:(

3 个答案:

答案 0 :(得分:1)

select distinct FirstName, LastName, table_2.status, CONCAT(FirstName, ' ', LastName) 
from table_1 inner join table_2 on table_1.key_2 = CONCAT('OFFLINE-', table_2.id) 
order by FirstName, LastName

答案 1 :(得分:0)

这有效:)

SELECT DISTINCT
    FirstName, 
    LastName, 
    table_2.status, 
    (select CONCAT(FirstName,' ',LastName) as Name from table_1 where id=receiver) as receiver, 
FROM table_1
INNER JOIN 
    table_2 on table_1.key_2 = CONCAT('OFFLINE-', table_2.id)
ORDER BY FirstName, LastName

答案 2 :(得分:0)

您可以使用别名而不是子查询来执行此操作:

SELECT DISTINCT
    t2.FirstName, 
    t2.LastName, 
    t2.status, 
    CONCAT(t1.FirstName,' ', t1.LastName) as receiver
FROM table_1 t1
INNER JOIN 
    table_2 t2 on t1.key_2 = CONCAT('OFFLINE-', t2.id)
ORDER BY t1.FirstName, t1.LastName