简体   繁体   English

从一个表中选择另一个ID,然后在另一个表中将其替换为与第二个表不同的char

[英]Select from one table where id in another and replace integer with char varying from second table

I have two tables, one is a user log which stores the user by number 我有两个表,一个是用户日志,按数字存储用户

timestamp / user_id / transaction_id / amount

the other is a user table which has the users number and their full name 另一个是用户表,其中包含用户号及其全名

user_id / fullname

I want to select the entire user log and display it, but instead of displaying their number, display their full name from the other table, but I can't get it working. 我想选择整个用户日志并显示它,但是没有显示他们的号码,而是从另一个表中显示了他们的全名,但是我无法使其正常工作。 I keep modifying the sql and breaking it. 我不断修改SQL并将其破坏。 Is there a way to accomplish this with php postgresql or should I use a function? 有没有办法用php postgresql完成此操作,还是应该使用一个函数? I keep getting an error that user_id is integer and the fullname is not Please assist. 我不断收到一个错误信息,说user_id是整数,全名不是。请协助。

    $query = "SELECT * FROM user_log 
    INNER JOIN user_staff
ON user_log.user_id=user_staff.user_name
ORDER BY user_log_id DESC LIMIT 200;";

    $result = pg_query($query); 
    if (!$result) { 
        echo "Problem with query " . $query . "<br/>"; 
        echo pg_last_error(); 
        exit(); 
    } 

    while($myrow = pg_fetch_assoc($result)) { 
        printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['timestamp'], htmlspecialchars($myrow['user_id']), htmlspecialchars($myrow['transaction_id']), htmlspecialchars($myrow['amount']));
    } 
    ?> 

Use this query: 使用此查询:

SELECT "timestamp", fullname, transaction_id, amount
FROM user_log
JOIN users USING (user_id)

Note that "timestamp" is a SQL reserved word and you should not use it for a column name. 请注意,“ timestamp”是SQL保留字,您不应将其用作列名。 If you must use it, put it in double quotes. 如果必须使用它,请将其放在双引号中。

Perhaps something like: 也许像这样:

SELECT user_log.timestamp, users.fullname, user_log.transaction_id, user_log.amount
FROM user_log
INNER JOIN users
ON users.user_id=user_log.user_id 
ORDER BY user_log_id 
DESC LIMIT 200;

You can read up on SQL Joins here: http://www.w3schools.com/sql/sql_join.asp 您可以在此处阅读有关SQL Joins的内容: http : //www.w3schools.com/sql/sql_join.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM