简体   繁体   English

SQL-如何从3个表中查询(查询中的查询?)?

[英]SQL - How to Query from 3 tables (query in query?)?

I want to know how to complete this query correctly. 我想知道如何正确完成此查询。

I wish to export a full list of votes from all ips used by an user. 我希望从用户使用的所有IP导出投票的完整列表。


My database have 3 tables storing the relatives data => 我的数据库有3个表,存储亲戚数据=>

votes = vote_site_id | 票数= vote_site_id | vote_ip | 投票| vote_time 投票时间

connexions_ip = adresse_ip | connexions_ip = adresse_ip | user_id | user_id | connexion_time 连接时间

users = user_id | 用户= user_id | user_name | 用户名| user_ip user_ip


So actually I have this query to have all connexions_ip from one user => 所以实际上我有这个查询来拥有一个用户的所有connexions_ip =>

SELECT c.adresse_ip, c.user_id, u.user_name
    FROM connexions_ip c 
    LEFT JOIN users u ON u.user_id = c.user_id
WHERE u.user_id = '1'

And this query to have all votes from one user => 并且此查询具有一个用户的所有投票=>

SELECT v.vote_site_id, v.vote_ip, v.vote_time, u.user_name
    FROM votes v 
    LEFT JOIN users u ON u.user_ip = v.vote_ip 
WHERE user_id = '1'

I tried with subquery but I have this error "#1242 - Subquery returns more than 1 row" 我尝试使用子查询,但出现此错误“#1242-子查询返回多于1行”

SELECT v.vote_site_id, v.vote_ip, v.vote_time, u.user_name
    FROM votes v 
    LEFT JOIN users u ON (
SELECT c.adresse_ip
    FROM connexions_ip c 
    LEFT JOIN users u ON u.user_id = c.user_id
WHERE u.user_id = '1'
)
 = v.vote_ip 
WHERE user_id = '1'

Thanks for your help. 谢谢你的帮助。

You can join all the table 你可以参加所有桌子

SELECT c.adresse_ip, c.user_id, u.user_name
     , v.vote_site_id, v.vote_ip, v.vote_time
FROM   users u
       LEFT JOIN connexions_ip c ON u.user_id = c.user_id
       LEFT JOIN votes v ON u.user_ip = v.vote_ip 
WHERE  u.user_id = '1'

I choosed the table users as the base for FROM because is the only table with a condition. 我选择表用户作为FROM的基础,因为这是唯一一个有条件的表。

try this: 尝试这个:

select a.*,b.* from (SELECT c.adresse_ip, c.user_id, u.user_name
    FROM connexions_ip c 
    LEFT JOIN users u ON u.user_id = c.user_id
WHERE u.user_id = '1')a left join (SELECT u.user_id,v.vote_site_id, v.vote_ip, v.vote_time, u.user_name
    FROM votes v 
    LEFT JOIN users u ON u.user_ip = v.vote_ip 
WHERE user_id = '1')b on a.user_id  = b.user_id 

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

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