Tomek
Tomek

Reputation:

Why doesn't this SQL statement work?

SELECT * FROM table1, table2
WHERE table1.user_id = table2.id
AND table1.content = news
AND table1.content_id = 1

that wont work. cant u have two "AND" in a sql statement??

//Tomek

Upvotes: 1

Views: 511

Answers (6)

marc_s
marc_s

Reputation: 754468

  • What do table1 and table2 look like? Can you paste a create script?
  • I would STRONGLY recommend to use the proper JOIN syntax:

    select * from table1 inner join table2 on table1.user_id = table2.id ......

  • what datatypes is "table1.content" ?

You can most definitely have a lot more than just 2 AND statements in a SQL query - any database that really support any of the SQL-xx standards will support this...

Upvotes: 1

HLGEM
HLGEM

Reputation: 96552

First let's start with getting rid of that old-style join so that the join and where clauses are clearly separated to make understanding much easier.

SELECT * FROM table1 t1.
JOIN table2 t2
ON t1.user_id = t2.id
WHERE t1.content = news
AND t1.content_id = 1

Now let's discuss what the problem might be. First what error are you receiving as this could be perfectly acceptable syntax? Could the problem be that you have not noted which table news is to come from? If it is in both tables you could be getting an error there. If news is meant to be the value of the column you would want it to be 'news' instead of news. It could also simply be that no records meet your conditions.

Further it is a bad practice to ever use select * and it should never be used in a join as you are returning at least one field twice and that is wasteful of both database and network resources. Always specify only the columns you need. This wastes lots of resources every day when lazy programmers do this in every query.

Upvotes: 1

Epitaph
Epitaph

Reputation: 3148

I liked cmartin's response. Also, you can use more than one AND, if needed.

Upvotes: 0

SQLMenace
SQLMenace

Reputation: 135001

let me rewrite that for you with a JOIN statement since it is not 1995 anymore, you also need quotes around news

SELECT * FROM table1 t1
inner join table2 t2 on t1.user_id = t2.id
AND t1.content = 'news'
AND t1.content_id = 1

Upvotes: 3

user54650
user54650

Reputation: 4426

you probably want to quote 'news' as a string... You also probably want to use an inner join instead (much more efficient)

SELECT * FROM table1
INNER JOIN table2 ON table1.user_id = table2.id 
WHERE table1.content = 'news' 
AND table1.content_id = 1

Upvotes: 11

Esko
Esko

Reputation: 29367

news is what? Some sort of parameter? Value of the field? A word which should occur in the field? Most likely your syntax is wrong, see W3Schools WHERE and W3Schools AND/OR operators pages for more information.

Upvotes: 4

Related Questions