rajiv gaur
rajiv gaur

Reputation: 43

mysql query to assign value to the same variable from different columns

I have a table which has many columns but there are two main columns called District and State. My sql query is as follows.

$query = "SELECT * FROM table WHERE District = '" . $var . "' ORDER BY Date DESC";

this query returns me data from the district column.

Now this is what I want.In some rows the District column is empty, so in that case I want the query to lift data from State column. Is that possible?

Can that be done in mysql query or will I have to write something in php?

Upvotes: 2

Views: 372

Answers (3)

arkascha
arkascha

Reputation: 42915

SELECT * 
FROM table 
WHERE District = '$var' 
  OR (District='' AND State='var') 
ORDER BY Date DESC

Upvotes: 1

xlecoustillier
xlecoustillier

Reputation: 16351

$query = "SELECT * FROM table WHERE District = '" . $var . "' OR State = '" . $var . "' ORDER BY Date DESC";

Upvotes: 0

John Woo
John Woo

Reputation: 263703

what do you mean by empty? If it is NULL then you should use COALESCE

SELECT *, COALESCE(District, State) NewDistrict
FROM...

but if it is empty as ''. then

SELECT *, IF(District = '', State, District) NewDistrict
FROM...

Upvotes: 6

Related Questions