简体   繁体   English

SQL查询从表1和表2中选择?

[英]SQL query to select from table 1 and table 2?

I'm struggling to find an answer to a query I want to run. 我正在努力寻找要运行的查询的答案。 I want to 我想要

SELECT * FROM users AND tempusers WHERE username='joe'

Both tables have a column named username. 两个表都有一个名为用户名的列。 I keep getting hit with SQL 1064 syntax error, which isn't very helpful to me. 我一直受到SQL 1064语法错误的打击,这对我不是很有帮助。

DB structure: 数据库结构:

DB Name : mydb 数据库名称 :mydb

Table : users Columns : id, username, email, password. :用户 :ID,用户名,电子邮件,密码。

Table : tempusers Columns : id, username, email, password, activationcode. :tempusers :id,用户名,电子邮件,密码,激活码。

The error you're getting is because you can't select from table1 AND table2 ; 您收到的错误是因为无法从table1 AND table2选择; that's not usually valid SQL syntax. 通常这不是有效的SQL语法。 (I say "usually" because MySQL has some proprietary syntax that most other databases don't use.) (我之所以说“通常”,是因为MySQL具有一些其他大多数数据库都不使用的专有语法。)

It doesn't appear that a JOIN will work, because you're not describing that sort of relation between the tables. 似乎JOIN不会起作用,因为您没有描述表之间的这种关系。

This should work if both tables have exactly the same structure (column names and types and the same number of columns): 如果两个表都具有完全相同的结构(列名称和类型以及相同的列数),则此方法应该起作用:

SELECT * FROM users WHERE username = 'joe'
UNION ALL
SELECT * FROM tempusers WHERE username = 'joe'

If the tables don't have the same exact schema, you'll have to name the columns in at least the first table SELECT : 如果这些表没有完全相同的架构,则必须至少在第一个表SELECT命名这些列:

SELECT 
  username, id, username, email, password, '' as activationcode
FROM 
  users 
WHERE 
  username = 'joe'
UNION ALL
SELECT 
  username, id, username, email, password, activationcode
FROM 
  tempusers
WHERE 
  username = 'joe'

You may have to provide blank spaces in place of '' for the activationcode in the first select, or use a value of the proper type for the activationcode column if it's not a character column (for instance, 0 for an integer column). 您可能必须在第一个选择中为activationcode提供空格来代替'' ,或者如果activationcode列不是字符列(例如,对于整数列为0 ),请为该activationcode列使用正确类型的值。

Potentially this will resolve the error and help you to think about why the error is occuring: 可能会解决该错误,并帮助您考虑发生错误的原因:

SELECT * 
FROM   users, tempusers 
WHERE  users.username='joe' 
       or tempusers.username='joe'

However - I strongly recommend using a proper join here. 但是 -我强烈建议您在此处使用适当的联接。 This query will be slow, and cumbersome. 该查询将很慢且麻烦。 Ken White's answer is bang on (and should definitely be the accepted one) - I'm only posting this to help you to understand the initial error more clearly (the dbms is unable to differentiate which table's username column you are referring to and can't refer to both in one statement). 肯·怀特(Ken White)的答案是肯定的(肯定应该被接受)-我只是为了帮助您更清楚地了解初始错误(dbms无法区分您要引用的表的用户名列而已)就可以了。 (请在一个声明中同时引用两者)。

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

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