John Bowlinger
John Bowlinger

Reputation: 1579

How do I select all rows in a MySQL column

This seems to be an easy question but I can't for the life of me find an answer. How do I select all rows in a column regardless of value? For instance if I want everything in the column location:

"SELECT * FROM whateverTable WHERE id='$id' AND date='$date' AND location='I don't care, return everything'"

Keep in mind that I need location in there because I'm getting a dynamic URL query to this database, otherwise I would have just left it out.

Edit I've read some of the answers and shame on me for not making myself clearer. I'm trying to see if a MySQL query where you can select every row in a column is possible without the need for this:

if ($location == '') {
  "SELECT * FROM whateverTable WHERE id='$id' AND date='$date'"
} else {
  "SELECT * FROM whateverTable WHERE id='$id' AND date='$date' AND location='$location'"
}

Rather than hacking up my code like that (because I have a hell of alot more query clauses in my real code), I'm trying to see if something like this is possible :

"SELECT * FROM whateverTable WHERE id='$id' AND date='$date' AND location='%'"

or this:

"SELECT * FROM whateverTable WHERE id='$id' AND date='$date' AND location='.*'"

But I'm not having any luck. If it's not, I'll just move on. Sorry for not making myself clearer

Upvotes: 5

Views: 45198

Answers (5)

C_Sutt
C_Sutt

Reputation: 202

I think you're looking for a sub query?

SELECT * FROM whateverTable WHERE location IN (SELECT location FROM whateverTable);

Upvotes: 0

Carlos
Carlos

Reputation: 1

Replace equal symbol : "=" by LIKE

SELECT * FROM whateverTable WHERE id='$id' AND date='$date' AND location LIKE '%'

Upvotes: 0

JustinDanielson
JustinDanielson

Reputation: 3185

If you're dynamically building the query just check if location is null or the empty string and then omit that part of the query.

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838116

As you said in your question, you should build the query dynamically and just omit that field. The query would then become:

SELECT * FROM whateverTable
WHERE id = '$id'
AND date = '$date'

If you can't do that for some reason, you could try something like this:

SELECT * FROM whateverTable
WHERE id = '$id'
AND date = '$date'
AND (location='$location' OR '$location' = '')

Setting $location to the empty string will cause all locations to be returned.

And don't forget to correctly escape your strings to avoid SQL injection attacks.

Upvotes: 6

hafichuk
hafichuk

Reputation: 10781

SELECT location FROM whateverTable will return you every single row/value in the location column.

Add your where clause if you want to start filtering the results down.

Upvotes: 1

Related Questions