简体   繁体   English

如何从一个查询中提取多个用​​户信息?

[英]How can I pull multiple user info from one query?

I have an invoice table that holds the id of the user that sent the invoice ( from_id ) and the user that received the invoice ( to_id ). 我有一个发票表,其中包含发送发票的用户( from_id )和收到发票的用户( to_id )的to_id

I want to be able to pull both of their info from the profile table but I am unable to figure out how. 我希望能够从个人资料表中提取他们的两个信息,但我无法弄清楚该怎么做。

Below is the query I'm running that let's me pull info for just one user ( from_id ) because of the join. 下面是我正在运行的查询,由于连接,我只为一个用户( from_id )拉取信息。

SELECT jobs.title, profiles.display_name, invoice.to_id, invoice.from_id, invoice.amount
FROM (invoice) 
JOIN jobs ON jobs.job_id = invoice.job_id 
JOIN profiles ON invoice.from_id = profiles.user_id 
WHERE `invoice_id` = '3'

You can use the same table twice. 您可以使用同一张表两次。 Give them different aliased, which I think makes a query more readable anyway. 给他们提供不同的别名,无论如何我认为这会使查询更具可读性。

SELECT 
  j.title, 
  tp.display_name as to_name, fp.display_name as from_name, 
  i.to_id, i.from_id, 
  i.amount
FROM 
  invoice i
  JOIN jobs j ON j.job_id = i.job_id 
  JOIN profiles fp ON i.from_id = fp.user_id 
  JOIN profiles tp ON i.to_id = tp.user_id 
WHERE 
  i.invoice_id= '3'

You can join on a table more than once - in this case you need to join on the profiles table twice - once to get information about who the invoice is from and once to get the information about the user the invoice was sent to. 您可以在一个表上多次联接-在这种情况下,您需要在profiles表上联接两次-一次获取有关发票来源的信息,一次获取有关发票发送给用户的信息。

SELECT jobs.title
    , Profile_From.display_name AS [From]
    , Profile_To.display_name AS [To]
    , invoice.to_id
    , invoice.from_id
    , invoice.amount
FROM invoice 
JOIN jobs 
    ON jobs.job_id = invoice.job_id 
JOIN profiles Profile_From
    ON invoice.from_id = Profile_From.user_id 
-- You are just missing this part
JOIN profiles Profile_To
    ON invoice.to_id = Profile_To.user_id 
WHERE invoice_id= '3'

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

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