从两个单独的数据库表中选择值的最佳查询是什么?

时间:2014-09-05 11:41:40

标签: mysql

我试图根据这些数据库值输出内容,有两个表。用户和交易。用户具有以下字段:

id, username, firstname, lastname, usertype, points

第二个表,交易具有以下内容:

id, sender_id, receiver_id, points

sender_ID是发送积分的人的ID,receiver_id是接收人的ID,依此类推。

如何查询它以输出php中两个表的值,因此它将显示如下:

  

John Doe已经给Jane Doe送了3分。

4 个答案:

答案 0 :(得分:2)

你能试试吗?

在MYSQL中

SELECT CONCAT(u1.firstname,' ',u1.lastname) as sender,CONCAT(u2.firstname,' ',u2.lastname) as receiver,t.points as points
FROM transactions t
INNER JOIN users u1 ON u1.id=t.sender_id
INNER JOIN users u2 ON u2.id=t.receiver_id

在PHP中

您检索

echo $row['sender'].' has sent '.$row['receiver'].$row['points'].' points';

答案 1 :(得分:1)

只需对同一个表使用两个连接:

SELECT u1.firstname, u2.firstname, t.points FROM transactions t
INNER JOIN user u1 ON u1.id = t.sender_id
INNER JOIN user u2 ON u2.id = t.receiver_id
WHERE t.id = 1

答案 2 :(得分:1)

使用联接...

SELECT `t1`.`username`, `t2`.`username`, `t`.`points` FROM transactions `t`
INNER JOIN `table` `t1` ON `t1`.`id` = `t`.`sender_id`
INNER JOIN `table` `t2` ON `t2`.`id` = `t`.`receiver_id`
WHERE `t`.`id` = 1

答案 3 :(得分:0)

您好,您可以制作LEFT JOIN(例如:http://www.tutorialspoint.com/mysql/mysql-using-joins.htm),或者您可以使用此功能:

SELECT a.username, a.firstname, a.lasname, b.points, b.receiver_id
    FROM table1 a, table2 b
    WHERE table1.id = table2.sender_id;