I have the following method to create a search query that scores the search term by occurrence:
public function findAll($search, array $data = []) {
$query = DB::query("
SELECT
SQL_CALC_FOUND_ROWS
*,
SUM(MATCH(text) AGAINST('{$search}' IN BOOLEAN MODE)) as score
FROM " . DB::prefix() . "search_index
WHERE MATCH(text) AGAINST('{$search}' IN BOOLEAN MODE)
OR text LIKE '%{$search}%'
GROUP BY language_id, type, object_id
ORDER BY score DESC
LIMIT " . (int)$data['start'] . ", " . (int)$data['limit'] . "
");
$count = DB::query("SELECT FOUND_ROWS() AS total");
return [
'count' => (int)$count->row['total'],
'query' => $query->rows
];
}
This works beautifully, but I need to add in a query to the tag table so that it will increment the score and add items to the array for content that may not already exist in the main query:
$tags = DB::query("
SELECT * FROM " . DB::prefix() . "tag
WHERE tag = '{$search}'
");
Any ideas on how to implement this into the main query so that I'm only executing a single query?
I was able to combine these with a UNION query:
$query = DB::query("
(SELECT
SQL_CALC_FOUND_ROWS
type, object_id, language_id,
SUM(MATCH(text) AGAINST('{$search}' IN BOOLEAN MODE)) as score
FROM " . DB::prefix() . "search_index
WHERE MATCH(text) AGAINST('{$search}' IN BOOLEAN MODE)
OR text LIKE '%{$search}%'
GROUP BY language_id, type, object_id
ORDER BY score DESC
LIMIT " . (int)$data['start'] . ", " . (int)$data['limit'] . ")
UNION DISTINCT
(SELECT
section, element_id, language_id, tag
FROM " . DB::prefix() . "tag
WHERE tag = '{$search}')
");
Related
I am new in CodeIgniter, I want to count all rows from database table but i use limit in query and i want all count without use limit how can i do ?
my code is below :
$sql = " SELECT intGlCode,fkCategoryGlCode,'C' as acctyp,varEmail,varContactNo as phone,CONCAT(varFirstName,' ',varLastName) as name,dtCreateDate,chrStatus,varMessage as message
FROM " . DB_PREFIX . "Customer WHERE varEmail='$userEmail'
UNION
SELECT intGlCode,'' as fkCategoryGlCode,'P' as acctyp,varEmail,varPhoneNo as phone,varName as name,dtCreateDate,chrStatus,txtDescription as message FROM
" . DB_PREFIX . "Power WHERE varEmail='$userEmail' ORDER BY intGlCode DESC
LIMIT $start, $per_page ";
$query = $this->db->query($sql)
i use limit for pagination but i want to get all record from table.
You can add new column in both above and below UNION queries. It will be like below.
select (select count(*) from your_query), your_columns from query_above_union
UNION
select (select count(*) from your_query), your_columns from query_below_union
your_query = your full actual query your are using currently.
Although I am not sure about Codeigniter. But sure about SQl.
* If you count all records with all data including limit, than you can use this code. please check it. I hope it will works for you.*
$countsql = " SELECT intGlCode,fkCategoryGlCode,'C' as acctyp,varEmail,varContactNo as phone,CONCAT(varFirstName,' ',varLastName) as name,dtCreateDate,chrStatus,varMessage as message
FROM " . DB_PREFIX . "Customer WHERE varEmail='$userEmail'
UNION
SELECT intGlCode,'' as fkCategoryGlCode,'P' as acctyp,varEmail,varPhoneNo as phone,varName as name,dtCreateDate,chrStatus,txtDescription as message FROM
" . DB_PREFIX . "Power WHERE varEmail='$userEmail' ORDER BY intGlCode DESC";
$sql = $countsql. " LIMIT $start, $per_page";
$totalRecords = $this->db->query($countsql);
$result["total_rows"] = $totalRecords->num_rows();
$query = $this->db->query($sql);
$result["list"] = $query->result_array();
I'm trying to execute this query:
Query 1:
$query = "SELECT a.*, b.title_wo
FROM `worksheet_master` AS a
INNER JOIN `work_order` AS b ON a.wo_number = b.wo_number
WHERE CONCAT (a.`wo_number` like '" . $_POST["keyword"] . "%',
`title_wo` like '" . $_POST["keyword"] . "%')
ORDER BY a.`wo_number` DESC LIMIT 0,50";
Query 2:
$query = "SELECT a.*, b.title_wo
FROM `worksheet_master` AS a
INNER JOIN `work_order` AS b ON a.wo_number = b.wo_number
WHERE CONCAT (a.`wo_number` like '" . $_POST["keyword"] . "%',
`title_wo` like '" . $_POST["keyword"] . "%')
AND a.`status` = 'NULL'
ORDER BY a.`wo_number` DESC
LIMIT 0,50";
The Query 2 didn't gave me any result with AND clause while the Query 1 gave me the result.
Can anyone help me with this? I need to sort out the result which has the empty status in my table, that's why I added AND clause in Query 2 hoping the result will be as expected, but it's not.
Thank You.
Unless NULL is an actual string, you need to use IS NULL instead.
$query = "SELECT a.*, b.title_wo
FROM `worksheet_master` AS a
INNER JOIN `work_order` AS b ON a.wo_number = b.wo_number
WHERE CONCAT (a.`wo_number` like '" . $_POST["keyword"] . "%',
`title_wo` like '" . $_POST["keyword"] . "%')
AND a.`status` IS NULL
ORDER BY a.`wo_number` DESC
LIMIT 0,50";
I have two table :
news:
|id|title|image|timestamp|....
tags:
|id|books_id|...
for result:
("SELECT id,title,front_thumbs,short_desc,timestamp,counter,author,
FROM " . NEWS . " LEFT JOIN " . TAGS . " ON " NEWS . ".id = " . TAGS . ".content_id WHERE
" . TAGS . ".tags_id = ? AND approved = 1 ORDER BY timestamp DESC LIMIT 10", $id)
but I see this error:
Error: Column 'id' in field list is ambiguous
how do fix this error?
When both tables have same field name it gets ambiguous and to solve this
use SELECTNEWS.id or TAGS.id which table's id you are using:
"SELECT NEWS.id,title,front_thumbs,short_desc,timestamp,counter,author,
FROM " . NEWS . " LEFT JOIN " . TAGS . " ON " NEWS . ".id = " . TAGS . ".content_id WHERE
" . TAGS . ".tags_id = ? AND approved = 1 ORDER BY timestamp DESC LIMIT 10", $id)
You need alias. Yuo have 2 tables both with column id. In your select you request id without specifying which of them you need.
You need to specify table here (before id):
... ("SELECT id,title,front_thumbs,short ...
I need to have my results sorted by "ORDER BY prod_name" in my SQL statement but I cannot figure out get it to work. I tried after
$thisProduct .= " AND prod_type = 1 ORDER BY prod_name";
and also after
$thisProduct .= " AND ID = '" . mysql_real_escape_string($_GET['product']) . "' ORDER BY prod_name";
But I cannot get my results to sort correctly. Am I placing the order by in the wrong spot or did I query the DB incorrectly?
Thank you in Advance, I am still pretty new at MYSQL queries.
$thisProduct = "SELECT prod_name AS Name, days_span, CONCAT(LEFT(prodID,2),ID) AS ID, geo_targeting FROM products WHERE status = 'Active' AND vendID = ".$resort['vendID'];
if (isset($_GET['product']) AND is_numeric($_GET['product'])) {
$thisProduct .= " AND ID = '" . mysql_real_escape_string($_GET['product']) . "'";
}
else {
$thisProduct .= " AND prod_type = 1";
}
$thisProduct .= " LIMIT 1";
$getThisProduct = mysql_query($thisProduct);
if (!$getThisProduct/* OR mysql_num_rows($getThisProduct) == 0 */) {
header("HTTP/1.0 404 Not Found");
require APP_PATH . '/404.html';
die();
}
$thisProductData = mysql_fetch_assoc($getThisProduct);
You should have:
$thisProduct .= " ORDER BY prod_name";
$thisProduct .= " LIMIT 1";
(Note that the LIMIT 1 means you only get one record).
Assuming that your query is correct and you want the first product by name:
$thisProduct .= " ORDER BY prod_name LIMIT 1";
I believe it should go right before your "LIMIT 1", as in:
$thisProduct .= " ORDER BY prod_name LIMIT 1";
Insert it before the LIMIT
$thisProduct .= " ORDER BY prod_name LIMIT 1";
You can the select syntax at http://dev.mysql.com/doc/refman/5.0/en/select.html
SELECT query usually takes following form
SELECT which_all_to_select
FROM which_table/tables
WHERE criteria
ORDER BY column_name ASC/DESC;
ASC ascending order, and DESC is descending order
This orders query results by column_name specified in ORDER BY clause .
I have this query:
$relevantwords = {"one" , "two" , "three" } ;
foreach ($relevantwords as $word)
{
$query .= "SELECT * FROM delhi_items WHERE heading like '%$word%' AND id!={$entry_row['id']} AND visible=1 UNION ALL " ;
}
$query = implode( " " , explode(" " , $query , -3) ) ;
$query .= " ORDER BY time_stamp DESC LIMIT 0, 20 " ;
$result_set = mysql_query($query, $connection);
This causes several duplicates in my resultset. Is there a way to detect and remove these duplicates from the resultset ? I know I should probably try to avoid the duplicates in the first place, but I am unable to figure that out.
Also I tried distinct keyword, it didn't work (because its a loop, the same entry is fetched again and again).
Laslty I am kind of an amateur so please tell me if I am doing something fundamentally uncool with such a long sql query in a for loop.
Thanks
This is not the right way to do this query; don't use UNION ALL with several queries.
Just use one query and use an OR between the relevant WHERE clause parts. It'll select each row just once, regardless of how many bits it matches.
I would try to have one SELECT and no UNION and DISTINCT. It will probably be a faster query:
$relevantwords = {"one" , "two" , "three" } ;
$querycondition = "" ;
foreach ($relevantwords as $word)
{
$querycondition .= " heading LIKE '%$word%' OR"
}
$querycondition = substr($querycondition ,0 ,strlen($querycondition)-2 ) ;
$query = " SELECT * "
. " FROM delhi_items "
. " WHERE ( "
. $querycondition
. " ) "
. " AND id!={$entry_row['id']} "
. " AND visible=1 "
. " ORDER BY time_stamp DESC "
. " LIMIT 0, 20 " ;
$result_set = mysql_query($query, $connection);
Use DISTINCT:
SELECT DISTINCT * FROM ...
UPDATE:
Actually DISTINCT doesn't work since the un-duping would happen before the records are merged with each other in the UNION ALL.
To do what you are trying to do, you want the SELECT DISTINCT * to happen outside the union-ing of all the records.
Do the selecting and union-ing inside a derived table:
SELECT DISTINCT * FROM
(SELECT * FROM TABLE WHERE ...
UNION ALL
SELECT * FROM TABLE WHERE ...
) t
ORDER BY ...