Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Another WHERE clause if there is no result

Tags:

mysql

What is the best way to do this in one query in mysql?

SELECT * FROM products WHERE language = 1

if there is no result

SELECT * FROM products WHERE language = 2 AND country = 1

if there is no result

SELECT * FROM products WHERE language = 2 AND country = 2
like image 245
jimmy Avatar asked Apr 24 '13 13:04

jimmy


People also ask

What happen if where clause is not given in query?

If the given condition does not match any record in the table, then the query would not return any row.

How would you return data from 2 tables even if there are no matches?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.

Is it possible to have a select statement without where clause?

you can see Select statement used without Where condition to fetch records from Ztable.

Can we use where clause after having clause?

You can create a WHERE clause and HAVING clause involving the same column. To do so, you must add the column twice to the Criteria pane, then specify one instance as part of the HAVING clause and the other instance as part of the WHERE clause.


2 Answers

I've edited it to make it work, but it is no longer elegant.


The original (without the last and not exists) had a flaw.

Turns out this isn't as clever as I thought. See comments below. It fails if the first and third queries return data. It does work if you have only one union, but not two or more.


It's quite easy in mysql:

select SQL_CALC_FOUND_ROWS * from products where language = 1
union
SELECT * FROM products WHERE language = 2 AND country = 1 and found_rows()=0
union
SELECT * FROM products WHERE language = 2 AND country = 2 and found_rows()=0 
AND not exists(select * from products where language = 1)

See the discussion of found_rows() and SQL_CALC_FOUND_ROWS here: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows

like image 137
Shawn Balestracci Avatar answered Sep 25 '22 19:09

Shawn Balestracci


You could use something like the following: (edited to use EXISTS and LIMIT based on comments).

(
SELECT * FROM products WHERE language = 1
)
UNION
(
SELECT * FROM products WHERE language = 2 AND country = 1
AND NOT EXISTS(SELECT count(*) FROM products WHERE language = 1 limit 1)
)
UNION
(
SELECT * FROM products WHERE language = 2 AND country = 2 
AND NOT EXISTS(SELECT count(*) FROM products WHERE language = 2 AND country = 1 limit 1)
AND NOT EXISTS(SELECT count(*) FROM products WHERE language = 1 limit 1)
)

You check with nested queries and count(*) that previous queries were NULL.

like image 39
Menelaos Avatar answered Sep 23 '22 19:09

Menelaos