Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select ... where id = any value. is it possible?

look at this table please

table
|id| |name| |order|

i must get the rows, where name = something and order = somevalue

so i write

select `id` from `table` where `name` = 'something' and `order` = 'somevalue'

but depend on php logic, sometimes i need to get all rows, where name = something, independently of order value. i don't want to change the query structure, because in practise there are many number of fields, and possible count of queries will become very big. so i want to save the structure of query, and when i need to select just by name, i want to write something like this:

select `id` from `table` where `name` = 'something' and `order` = any value 

is it possible?

thanks

like image 987
Simon Avatar asked May 20 '10 22:05

Simon


2 Answers

Well, it's kind of a hack, but if you really need to do this, it'll work like this:

select `id` from `table` where `name` = 'something' and `order` = `order`

Then you're just saying "wherever order is the same as itself", so it's always true.

like image 163
Chad Birch Avatar answered Nov 05 '22 04:11

Chad Birch


No, this is not possible. You need to change the structure (optionally to a LIKE so you can use '%', but that's very ugly).

However, you don't need to write a different query to handle every possible combination. You can simply create the query dynamically:

//create base query
$query = "select `id` from `table` where `name` = 'something' ";

//add order if we need it
if ($use_order)
  $query .= "and `order` = 'somevalue' ";

//repeat for any other optional part

Note that you should of course still take proper measures to avoid SQL injection and other security issues - I have not included this here in order to keep things simple.

like image 37
Michael Madsen Avatar answered Nov 05 '22 04:11

Michael Madsen