我有3行的表信息:id,monter1,monter2。 Monter1和monter2是我要加入的表monterzy(id,name,surname)的id。问题是我无法在php中进行正确的查询以获取这些值。目前我有:
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
我想扩展它以获得monter2和相应的名字和姓氏。我在谷歌搜索过,有AS的例子,但我不知道怎么做。谢谢!
答案 0 :(得分:0)
您需要使用不同的别名
连接同一个表两次SELECT info.id,
m1.name as m1_name, m1.surname as m1_surname,
m2.name as m2_name, m2.surname as m2_surname
FROM info
INNER JOIN monterzy m1 ON info.monter1 = m1.id
INNER JOIN monterzy m2 ON info.monter2 = m2.id
答案 1 :(得分:0)
您只需要对表进行别名。也就是说,对于同一个表的每个连接,给它一个不同的别名(名称),以便查询的其余部分知道哪个是哪个。像这样:
SELECT
info.id,
m1.name,
m1.surname,
m2.name,
m2.surname
FROM
info
INNER JOIN monterzy AS m1 ON info.monter1 = m1.id
INNER JOIN monterzy AS m2 ON info.monter2 = m2.id
注意每个联接如何为AS someAlias
添加一个新名称,仅用于此查询。以及查询的其余部分如何引用该别名而不是表名。
答案 2 :(得分:0)
您需要使用表别名:
SELECT info.id, m1.name as name1, m1.surname as surname1, m2.name as name2, m2.surname as surname2
FROM info
INNER JOIN monterzy m1 ON info.monter1 = m1.id
INNER JOIN monterzy m2 ON info.monter2 = m2.id;
答案 3 :(得分:0)
您可以使用左连接
SELECT
info.id,
m1.name,
m1.surname,
m2.name,
m2.surname
FROM
info
INNER JOIN monterzy AS m1 ON info.monter1 = m1.id
LEFT JOIN monterzy AS m2 ON info.monter2 = m2.id