【问题标题】:SQL SELECT with JOIN and WHERE clause - selecting one record from two tables带有 JOIN 和 WHERE 子句的 SQL SELECT - 从两个表中选择一个记录
【发布时间】:2018-01-03 17:00:16
【问题描述】:

我得到了这样的东西:

MySqlCommand sqlcmd = new MySqlCommand(@"SELECT Pupil.*, Instructor.* 
    FROM Pupil
    INNER JOIN Instructor ON Pupil.email = Instructor.email
    WHERE Pupil.email = '" + userEmail.Text + "'
      and Pupil.password = '" + userPassword.Text + "'", sqlconn);

我需要获取隐藏在第一个或第二个表中的记录。我检查并将相同的数据插入到第二个表中。此 SELECT 向我显示了公共记录,但我只想要第一个或第二个表中的唯一记录。

【问题讨论】:

  • 您应该始终使用参数化 SQL 以使您的代码更清晰,避免转换问题,并避免 SQL 注入攻击。
  • 您可以进行完全外连接,然后以编程方式过滤掉两边不包含 NULL 的记录,左表或右表中具有 NULL 的记录将是您唯一的记录。希望这就是你要找的。​​span>
  • 问题不清楚。表中的记录是如何隐藏的?您想要来自第一个第二个表的唯一记录是什么意思?你想从哪个表中记录?作为程序员,我们倾向于寻找字面意思,尤其是在讨论代码本身时,因为这是我们交流的唯一方式。所以从这个角度写出要理解的问题是有帮助的。
  • 好的,隐藏意味着它只是在表中。我为一个独特的短语道歉。我只是想说:我将数据插入到第一个或第二个表中。我如何输入一个查询,它会知道数据何时不在第一个表上,它需要在第二个表中搜索?

标签: c# mysql sql


【解决方案1】:

根据您上面的评论,我修改了查询。以下是示例数据的两个示例:

学生

  • Adam@abc.com
  • Bob@abc.com

教师

  • Bob@abc.com(请注意您的数据结构实际上允许这样做)
  • Chris@abc.com

查询

/* Adam is a pupil but not an instructor */
select Pupil.*
from Pupil
left join Instructor on Pupil.email = Instructor.email
where Instructor.email is null
  and Pupil.email = 'Adam@abc.com'
union 
select Instructor.*
from Instructor
left join Pupil on Pupil.email = Instructor.email
where Pupil.email is null
  and Instructor.email = 'Adam@abc.com';

/* Chris is an instructor but not a pupil */
select Pupil.*
from Pupil
left join Instructor on Pupil.email = Instructor.email
where Instructor.email is null
  and Pupil.email = 'Chris@abc.com'
union 
select Instructor.*
from Instructor
left join Pupil on Pupil.email = Instructor.email
where Pupil.email is null
  and Instructor.email = 'Chris@abc.com';

您可以在以下位置找到一个工作示例:http://sqlfiddle.com/#!9/c490c7/28

【讨论】:

  • 我只需要从两个表中选择记录,因为它可能在第一个表中,也可能在第二个表中。就是这样。
  • 我将语法更改为:MySqlCommand sqlcmd = new MySqlCommand("select Pupil.* from Pupil left join Instructor on Pupil.email = Instructor.email where Instructor.email is null and Pupil.email = '" + userEmail.Text + "' and Pupil.password = '" + userPassword.Text + "' union select Instructor.* from Instructor left join Pupil on Pupil.email = Instructor.email where Pupil.email is null and Instructor.email = '" + userEmail.Text + "' and Instructor.password = '" + userPassword.Text + "'", sqlconn); 并发生未处理的异常...您有什么想法吗?
  • 我也得到:使用的 SELECT 语句有不同的列数
猜你喜欢
  • 1970-01-01
  • 2018-08-18
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多