Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query: Join two tables with where clause

Tags:

sql

sql-server

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

SELECT *
FROM table1
WHERE Date = CURDATE()

There's a column in table1 which is called h_id and a table2 with the columns h_id and name

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

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( )
like image 226
Mexxer Avatar asked Mar 01 '12 14:03

Mexxer


People also ask

Can I use join with WHERE clause in SQL?

To use the WHERE clause to perform the same join as you perform using the INNER JOIN syntax, enter both the join condition and the additional selection condition in the WHERE clause. The tables to be joined are listed in the FROM clause, separated by commas. This query returns the same output as the previous example.

Can we use WHERE instead of join?

Actually you often need both "WHERE" and "JOIN". "JOIN" is used to retrieve data from two tables - based ON the values of a common column. If you then want to further filter this result, use the WHERE clause. For example, "LEFT JOIN" retrieves ALL rows from the left table, plus the matching rows from the right table.

Should I put condition in join or WHERE clause?

It is better to add the condition in the Join. Performance is more important than readability. For large datasets, it matters.

Can we use WHERE and having together in a query?

A query can contain both a WHERE clause and a HAVING clause. In that case: The WHERE clause is applied first to the individual rows in the tables or table-valued objects in the Diagram pane. Only the rows that meet the conditions in the WHERE clause are grouped.


2 Answers

It might be case sensitive.

or

does table1 have field2 column?

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:

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.

like image 107
aF. Avatar answered Oct 03 '22 17:10

aF.


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

like image 26
Diego Avatar answered Oct 03 '22 15:10

Diego