SQL 查询:使用 where 子句连接两个表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9517915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:37:02  来源:igfitidea点击:

SQL query: Join two tables with where clause

sqlsql-server

提问by Mexxer

I have a problem with a SQL query. I got the following query working, which pretty basic:

我的 SQL 查询有问题。我得到了以下查询,这是非常基本的:

SELECT *
FROM table1
WHERE Date = CURDATE()

There's a column in table1 which is called h_idand a table2with the columns h_idand name

在 table1 中有一个列被调用h_id,一个table2h_idname

I want to join those two tables so that I have the names out of table 2 from the current date.

我想加入这两个表,以便我从当前日期获得表 2 中的名称。

I tried this, but it doesn't seem to work

我试过这个,但它似乎不起作用

SELECT t2.name, t1.field2
FROM table1 t1
INNER JOIN table2 t2 ON t1.H_ID = t2.H_ID
WHERE t1.Date = CURDATE( )

回答by aF.

It might be case sensitive.

它可能区分大小写。

or

或者

does table1 have field2 column?

table1 有 field2 列吗?

If not/so, and according to your question, try it like this:

如果不是/所以,根据你的问题,试试这样:

SELECT t2.name
FROM table1 t1
INNER JOIN table2 t2 ON t1.h_id = t2.h_id
WHERE t1.Date = CURDATE()


Another possibility is the where clause, try it like this:

另一种可能是 where 子句,试试这样:

SELECT t2.name
FROM table1 t1
INNER JOIN table2 t2 ON t1.h_id = t2.h_id
WHERE convert(varchar, t1.Date, 112) = convert(varchar, getdate(), 112)


A last possibility is that there isn't any h_id equal from table1 and table2.

最后一种可能性是 table1 和 table2 中没有任何 h_id 相等。

回答by Diego

try to remove the WHERE t1.Date = CURDATE( )and see if your record is returned. If it is, there is a problem with your CURDATE( ), try using getdate() or try to format the date

尝试删除WHERE t1.Date = CURDATE( )并查看您的记录是否返回。如果是,则您的 存在问题,请CURDATE( )尝试使用 getdate() 或尝试格式化日期

回答by Mosty Mostacho

SQL Server does not support curdate(). That's for MySQL.

SQL Server 不支持curdate(). 那是针对 MySQL 的。

The appropriate function is getdate()

合适的函数是 getdate()

Here is a link to the official documentation

这是官方文档的链接

Edit:

编辑:

As you said in a comment, if getdate()doesn't work then you're using MySQL, then. Try this:

正如您在评论中所说,如果getdate()不起作用,那么您正在使用 MySQL,然后。尝试这个:

SELECT t2.name, t1.field2
FROM table1 t1
INNER JOIN table2 t2 ON t1.H_ID = t2.H_ID
WHERE date(t1.Date) = date(CURDATE())

回答by Mosty Mostacho

Try:

尝试:

SELECT t2.name, t1.field2
FROM table1 t1
LEFT JOIN table2 t2 ON t1.H_ID = t2.H_ID
WHERE t1.[Date] = GETDATE( )

or alternatively (MySQL):

或者(MySQL):

SELECT t2.name, t1.field2
FROM table1 t1
LEFT JOIN table2 t2 ON t1.H_ID = t2.H_ID
WHERE t1.`Date` = CURDATE( )