查询以获取所有具有理由的罪行以及罪犯和警察的名字,这就是我想要实现的目标。
这是我尝试过的:
SELECT crimes.user_police_id, crimes.user_criminal_id, crimes.reason, users.name
FROM `users`
INNER JOIN `crimes` on users.id = crimes.user_criminal_id
只返回罪犯的名字......
表格结构
CREATE TABLE users (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(24)
);
INSERT INTO users (name) VALUES ("Divergent");
INSERT INTO users (name) VALUES ("SomeGuy");
CREATE TABLE crimes (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
user_criminal_id INT(11),
user_police_id INT(11),
reason VARCHAR(256)
);
INSERT INTO crimes (user_criminal_id, user_police_id, reason) VALUES (2, 1, "Corruption");
这样可行,但只有警察名字
SELECT crimes.user_police_id, crimes.user_criminal_id, crimes.reason, c.name, p.name
FROM crimes
JOIN users c on c.id = crimes.user_criminal_id
JOIN users p on p.id = crimes.user_police_id
答案 0 :(得分:1)
第二次加入users
获取警察名称。
SELECT crimes.user_police_id, crimes.user_criminal_id, crimes.reason, u1.name AS criminal u2.name AS police
FROM `users` AS u1
INNER JOIN `crimes` on u1.id = crimes.user_criminal_id
INNER JOIN `users` AS u2 ON u2.id = crimes.user_police_id
答案 1 :(得分:1)
你需要加倍加入。我更喜欢查询犯罪,所以你会明白为什么:
SELECT crimes.user_police_id, crimes.user_criminal_id, crimes.reason, c.name, p.name
FROM crimes
JOIN users c on users.id = crimes.user_criminal_id
JOIN users p on users.id = crimes.user_police_id