1

I have 2 select statements.

1- select sm.id, IFNULL(sm.unit_price,0) as unit_price       
   from crm_stock_manager sm
   left join crm_purchase_order_items poi on poi.id = sm.purchase_order_item_id and  poi.is_del = 0
   left join crm_products p on poi.product_id = p.id and p.is_del = 0
   where sm.is_del = 0 and IFNULL(sm.unit_price, '') != '' and p.id = 253 order by sm.created_on;

2- select 0 as id ,price as unit_price from crm_products where id = 253  and is_del=0;

If 1st select statement return an empty result, then i want to run 2nd select statement.

Please help me.

CodeCook
  • 190
  • 1
  • 4
  • 17

3 Answers3

5

This appears to work from a quick test I just did and avoids the need to check for the existence of x=1 twice.

SELECT SQL_CALC_FOUND_ROWS *
FROM mytable
WHERE x = 1

UNION ALL

SELECT *
FROM mytable
WHERE 
FOUND_ROWS() = 0 AND x = 2;

Another way is Subqueries with EXISTS or NOT EXISTS

SELECT column1 FROM t1 WHERE NOT EXISTS (SELECT * FROM t2);
Vineet1982
  • 7,730
  • 4
  • 32
  • 67
  • Has the behavior of FOUND_ROWS() across SELECTs in the same UNION query changed? I'm seeing this method working for MySQL 5.1.61 but not for 5.6.15. In the latter case, FOUND_ROWS() in the second SELECT seems to return for the previous query instead of for the previous SELECT. Am I missing something? – eirikir May 07 '14 at 20:23
  • Their is great difficulty between union and found rows but it depends on need and table schema – Vineet1982 May 08 '14 at 03:05
  • the not exists is a nice solution – Richie Aug 28 '14 at 05:08
1

If you need to select crm_products.price if srm_stock_manager.unit_price is NULL, you can use COALESCE and you need not 2 queries. You can change your first part of SELECT statement as follows and other part as necessary to get the result required.

SELECT sm.id, COALESCE(sm.unit_price, p.price) unit_price FROM...

This returns p.price value if sm.unit_price is NULL.

Further, refer mysql doc.

chandimak
  • 201
  • 3
  • 17
  • `IFNULL` or `COALESCE`. Refer [this](http://stackoverflow.com/questions/4747877/mysql-ifnull-vs-coalesce-which-is-faster). – chandimak Feb 27 '13 at 06:18
1

You can do it like this

$query1 = mysql_query("YOUR QUERY");
$row_count = mysql_num_rows($query1);
if($row_count==0) {
 $query1 = mysql_query("Your Second Query");
}

Remember to not use mysql_* functions as they are depreciated.

Hope This Helps

Roger
  • 1,693
  • 1
  • 18
  • 34