简体   繁体   English

从多个表合并这些mysql查询

[英]Combine these mysql queries from multiple tables

Let say I have a table with a list of users, and I retrieve the users table like this: 假设我有一个包含用户列表的表,我像这样检索users表:

SELECT userid FROM users WHERE year = 2012

That generates a list of users, more specifically, userid's (digits). 这将生成用户列表,更具体地说,是用户标识(数字)。

So, lets say our list looks like this now (random userids): 因此,可以说我们的列表现在看起来像这样(随机用户ID):

1234
9532
0983
2098
1980

In other table, we have the users favorite colors, one entry for each color. 在另一个表中,我们有用户喜欢的颜色,每种颜色一个。 So user 1234 could have multiple entries in the table (lets call it fav_colors): 因此,用户1234可能在表中具有多个条目(将其称为fav_colors):

1234 red
1234 blue
9532 yellow
9532 red
0983 blue
0983 purple

This is very simplified example of a concept I am trying to grasp. 这是我尝试掌握的概念的非常简化的示例。 How can I form one query to show me the users where the year is 2012 (from the first query), and who likes the color red? 如何构成一个查询,向用户显示2012年在哪里(从第一个查询开始),谁喜欢红色? I am having trouble combining the queries from the users table and the fav_colors table 我在合并来自users表和fav_colors表的查询时遇到问题

Thanks 谢谢

This should get you the results you're looking for 这应该为您提供所需的结果

SELECT u.userid, c.color
FROM users AS u
JOIN fav_colors AS c
  ON u.userid = c.userid
WHERE u.year = 2012
  AND c.color_name = 'red'

You need to use SQL Joins to link both tables and use a where clause for the year and the red color. 您需要使用SQL Joins链接两个表,并为年份和红色使用where子句。

See : http://www.w3schools.com/sql/sql_join.asp for more info on SQL Joins. 有关SQL联接的更多信息,请参见: http : //www.w3schools.com/sql/sql_join.asp

Tell me if you need more explanations. 告诉我是否需要更多说明。

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

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