简体   繁体   中英

two tables in one SQL, query

I have two tables

 ID_USER | USERNAME
   1       Max
   2       Jean
   3       Carl
   4       Sophie

and

ID_MONEY | ID_USER | MONEY
  1           4      1000
  2           2      1500
  3           3      1250
  4           1      920

I want to execute the second table SQL and order the results by username (alphabetically), in order to get this:

Carl have: 1250$
Jean have: 1500$
Max  have: 920$
Sophie have: 1000$

What type of query sould I execute? I tried,

SELECT * 
FROM $table_users 
WHERE id_user='$id_user' 
ORDER BY (SELECT username FROM $table_money WHERE id_user='$id_user') ASC 

but not results as expected.

You need an INNER JOIN . This can be done using joins, or with the WHERE clause.

SELECT USERNAME, MONEY
FROM $table_users
JOIN $table_money USING (ID_USER)
ORDER BY USERNAME

or

SELECT USERNAME, MONEY
FROM $table_users, $table_money
WHERE $table_users.ID_USER = $table_money.ID_USER
ORDER BY USERNAME

I guess table_money might have multiple money values for the same user and you would want total.

SELECT table_users.ID_USER, table_users.USERNAME, SUM(table_money.MONEY)
FROM table_users  INNER JOIN table_money ON table_users.ID_USER = table_money.ID_USER
GROUP BY table_users.ID_USER, table_users.USERNAME
ORDER BY table_users.USERNAME

Here, I am using concatenation function to join the strings.

select CONCAT(tu.username,' have: ',tm.money,'$') as RESULT
from [$table_users] as tu
inner join [$table_money] as tm
on tu.ID_USER = tm.ID_USER
order by RESULT ASC;

OUTPUT:-

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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