select from db sql query - sql

I have this query :
$query = mysql_query ("SELECT *
FROM saledb.application
WHERE app_id = (
SELECT app_id
FROM saledb.applicationdetails
WHERE is_hot = '1'
) LIMIT $Kvet,$Zet
");
And I have the following error:
Unable to save result set in
/home/lemondo/lemondosales.itnovations.ge/content/tpl/gtpl/main.php on
line 68
When I changing select item with MAX(app_id) it works but i need show all results. i know where is problem mysql cant choose in one query meny ID but i need alternativ query.

Use the IN predicate instead of = like os:
SELECT *
FROM saledb.application
WHERE app_id IN
(SELECT app_id
FROM saledb.applicationdetails
WHERE is_hot = '1');

$query = mysql_query ("SELECT * FROM saledb.application WHERE app_id IN (SELECT app_id FROM saledb.applicationdetails WHERE is_hot = '1') LIMIT $Kvet,$Zet");
That should do the trick. If you leave '=' and the subquery returns more than one row, you wil get that error. To match all the lines in saledb.application that have the app_id in the result set you need to use "IN" :)

Related

Laravel query builder whereRaw with convert to datatype returning different results

Here I have two similar queries that return the same result if I paste them directly on SMSS:
But when using Laravel's query builder I get different results:
//select count(*) from [tbl_rfaccount] where CONVERT(varchar, id) = 'test'
$count = DB::connection('sqlsrv_rf_user')->table('tbl_rfaccount')
->whereRaw("CONVERT(varchar, id) = ?", $request->input('username'))
->count();
//$count = 1
//select count(*) from [tbl_rfaccount] where id = CONVERT(binary(13), 'test')
$count = DB::connection('sqlsrv_rf_user')->table('tbl_rfaccount')
->whereRaw("id = CONVERT(binary(13), ?)", $request->input('username'))
->count();
//$count = 0
Why is that? I've using Laravel Telescope and the queries look exactly like those I ran on SSMS.
This is how the table looks like:

Number of rows of query - Yii

i want to get the number of rows returned by a query in Yii. This is my query :
$programsAlreadyExist = $connection->createCommand('
SELECT *
FROM `cat_programme`
WHERE `programme_code` = 513')
->queryAll();
The "COUNT" keyword should return a row containing the requested number. :-)
SELECT COUNT(*) FROM cat_programme WHERE programme_code = 513
Change the SELECT to:
SELECT count (*) FROM cat_programme WHERE programme_code = '513'
Thanks !!
You could also do if via the count() method
For ecample
$programsAlreadyExist = MyModel::find()
->where(['programme_code' => '513'])
->count();

Why SQL query return additional rows when using multiple OR condition?

Hello I have Filter option in my program.
When i use an single option like when i filter only by STATUS=SCHEDULED i get the correct list as shown bellow
But when i give multiple condition then the SQl query returns more additional rows irrelevant to the date. like bellow
i am trying to filter the order with STATUS=SCHEDULED and CUSTOMER ID=87.
I took reference from here1
here2
And bellow is my SQL query
SELECT
*
FROM
workforce_customerorder
WHERE
ORDER_ID LIKE '$sOrder'
UNION
SELECT
*
FROM
workforce_customerorder
WHERE
CUSTOMER_ID LIKE '%$sCustomerID%'
UNION
SELECT
*
FROM
workforce_customerorder
WHERE
AGENT_NUMBER LIKE '%$sAgentNumber%'
UNION
SELECT
*
FROM
workforce_customerorder
WHERE
STATUS LIKE
'$sStatus'
UNION
SELECT
*
FROM
workforce_customerorder
WHERE
GST_NUMBER LIKE '$sGST'
UNION
SELECT
*
FROM
workforce_customerorder
WHERE
DATE(ORDER_DATE) BETWEEN '$sOrderDateFrom' AND '$sOrderDateTo'
I need the best SQl query. Thanks in advance
Ok After I tried using AND this what i got
You should have just one query, with a WHERE clause that performs the filtering on only the columns that are set
SELECT *
FROM workforce_customerorder
WHERE
(ORDER_ID = COALESCE('$sOrder', ORDER_ID)) AND
(CUSTOMER_ID LIKE '%$sCustomerID%' OR '$sCustomerID' IS NULL) AND
(AGENT_NUMBER LIKE '%$sAgentNumber%' OR '$sAgentNumber' IS NULL) AND
(STATUS = COALESCE('$sStatus', STATUS)) AND
(GST_NUMBER = COALESCE('$sGST', GST_NUMBER)) AND
(DATE(ORDER_DATE) BETWEEN COALESCE('$sOrderDateFrom', ORDER_DATE) AND COALESCE('$sOrderDateTo', ORDER_DATE))
Note that LIKE without a wildcard is equivalent to =. I find it clearer to specify which are exact matches and which are sub-matches with different syntaxes.
Don't use a UNION. You should be using AND in a single WHERE clause.
This behavior you are witnessing is due to use of UNION, Omit UNION and use AND like:
SELECT * FROM workforce_customerorder
WHERE
ORDER_ID LIKE '$sOrder'
AND
CUSTOMER_ID LIKE '%$sCustomerID%'
AND
AGENT_NUMBER LIKE '%$sAgentNumber%'
....
When using UNION although one of the subsets may be empty you get the results from all other non empty subsets
If you are doing a UNION that means give me anything in either of these sets, or in both. Try using just AND if you want two+ conditions to be true
Using UNION, you merge your columns. Because you use the same data table in your unions, you have the same column multiple times. You should use AND instead in the WHEREstatement. Below is the corrected query.
SELECT *
FROM workforce_customerorder
WHERE
ORDER_ID LIKE '$sOrder'
AND CUSTOMER_ID LIKE '%$sCustomerID%'
AND AGENT_NUMBER LIKE '%$sAgentNumber%'
AND STATUS LIKE '$sStatus'
AND GST_NUMBER LIKE '$sGST'
AND DATE(ORDER_DATE) BETWEEN '$sOrderDateFrom' AND '$sOrderDateTo'
ok finally i found the solution
$query_order_id = ($sOrder != "") ? " AND (ORDER_ID LIKE '$sOrder') " : "";
$query_customer_id = ($sCustomerID != "") ? " AND (CUSTOMER_ID LIKE '%".$sCustomerID."' OR '".$sCustomerID."' IS NULL) " : "";
$query_sAgentNumber = ($sAgentNumber != "") ? " AND (AGENT_NUMBER LIKE '%".$sAgentNumber."%' OR '".$sAgentNumber."' IS NULL) " : "";
$query_sStatus = ($sStatus != "") ? " AND (STATUS LIKE '%".$sStatus."%' OR '".$sStatus."' IS NULL) " : "";
$query_sGST = ($sGST != "") ? " AND (GST_NUMBER LIKE '%".$sGST."%' OR '".$sGST."' IS NULL) " : "";
$query_sOrderDateFrom = ($sOrderDateFrom != "") ? " AND (DATE(ORDER_DATE) BETWEEN COALESCE('$sOrderDateFrom', ORDER_DATE) AND COALESCE('$sOrderDateTo', ORDER_DATE)) " : "";
//sql query here
$sql = "SELECT * FROM workforce_customerorder where ORDER_ID IS NOT NULL".$query_order_id.$query_customer_id.$query_sAgentNumber.$query_sStatus.$query_sGST.$query_sOrderDateFrom;
}
It is same as what #Caleth showed but the one which matched exactly is by applying ternary operator before passing the variable to SQL query. Thank you every one you answers...

Select distinct value count laravel

I have an orders table where there is a status column.
I am trying to get the count of each status like this :
$pending = Order::where('status','=','pending')->count();
$active = Order::where('status','=','active')->count();
But this is not efficient as am having to make one call for each status type.
How can I reduce number of queries ?
To make an SQL request:
SELECT count(DISTINCT `status_id`) FROM `dbname`.orders WHERE `user_id` = '2';
In Laravel you can try the following:
$user->orders()->distinct()->count(["status_id"]);
You could try
$orders = Order::select(DB::raw('count(*) as order_count, status'))
->groupBy('status')
->get();
here is the way you write ->
$users= DB::table('table_name')->distinct()->get(['column_name']);
$users_count = $users->count();

How to execute query with subqueries on a table and get a Rowset object as a result in Zend?

I'm currently struggling on how to execute my query on a Table object in Zend and get a Rowset in return. Reason I need particularly THIS is because I'm modifying a code for existing project and I don't have much flexibility.
Query:
SELECT *
FROM `tblname` ud
WHERE ud.user_id = some_id
AND
(
(ud.reputation_level > 1)
OR
(
(SELECT COUNT( * )
FROM `tblname` t
WHERE t.user_id = ud.user_id
AND t.category_id <=> ud.category_id
AND t.city_id <=> ud.city_id
) = 1
)
)
Is there a way to describe this query using Select object?
Previous SQL solution was very simple and consisted of one WHERE clause:
$where = $this->getAdapter()->quoteInto("user_id = ?",$user_id);
return $this->fetchAll($where);
I need to produce same type of the result (so that it could be processed by existing code) but for more complicated query.
Things I've tried
$db = Zend_Db_Table::getDefaultAdapter();
return $db->query($sql)->fetchAll();
---------------- OR ----------------------
return $this->fetchAll($select);
---------------- OR ----------------------
return $this->_db->query($sql)->fetchAll();
But they either produce arrays instead of objects or fail with Cardinality violation message.
I would appreciate any help on how to handle SQL text queries in Zend.
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
//change the fetch mode becouse you don't like the array
$dbAdapter->setFetchMode(Zend_Db::FETCH_OBJ);
$sql = "you're long sql here";
$result = $dbAdapter->fetchAll($sql);
Zend_Debug::dump($result);
exit;
For a list of all fetch modes go to Zend_Db_Adapter
To write you're query using Zend_Db_Select instead of manual string , look at Zend_Db_Slect