Im using this code to show the number of registers I have in tt_address in Page ID 68, and works fine, except that it doesnt show the hidden elements.
# Default PAGE object:
page = PAGE
page{
20 = CONTENT
20 {
table = tt_address
select{
selectFields = count(uid) AS count
pidInList = 68
where = deleted = 0
}
renderObj = COA
renderObj {
10 = TEXT
10 {
value = Status: {field:count}
insertData = 1
}
}
}
}
How could I count also the hidden records?
I think it is not possible to get hidden records using typoscript (no records from hidden, timed or access-protected pages can be selected!).
Reference link: http://wiki.typo3.org/TSref/select
You may need to use "userfunc" as given below:
Typoscript:
includeLibs.showHiddenElements = fileadmin/lib/showHiddenElements.php
page.20 =USER
page.20 {
userFunc =user_showHiddenElements->main
field = uid
table = tt_address
where = deleted = 0 and pid = 68
}
fileadmin/lib/showHiddenElements.php :
<?php
class user_ShowHiddenElements {
function main($content, $conf){
$res= $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
$conf[field], // SELECT ...
$conf[table], // FROM ...
$conf[where], // WHERE...
'', // GROUP BY...
'', // ORDER BY...
'' // LIMIT ...
);
return $res;
}
}
?>
You can't bypass the "enable fields" where clauses in a normal way, but TYPO3 allows to hack around that using a UNION query:
select {
selectFields = count(uid) AS count
pidInList = 68
where.data = TSFE:id
# we hack our way around the enablefields restriction
where.wrap = 0 UNION SELECT COUNT(*) as count FROM tt_address WHERE pid = 68
}
An alternative solution:
page{
24 = CONTENT
24.wrap = <div class="status_count">|</div>
24 {
table = tt_address
select {
selectFields = count(uid) AS count
pidInList = 68
where.data = TSFE:id
# we hack our way around the enablefields restriction
where.wrap = |0 UNION SELECT COUNT(*) as count FROM tt_address WHERE pid = 68
}
renderObj = COA
renderObj {
10 = TEXT
10.wrap = |</div><div style="display:none">
10 {
value = Status: {field:count}
insertData = 1
}
}
}
}
Thanks cweiske for giving me this idea.
This is the way: e.g. Showing deleted or hidden pages only
table = pages
select.pidInList = 1
select.where = deleted=1 or hidden=1 UNION SELECT * FROM pages WHERE 1=0
This works 'cause the enablefields are appended to the query. Union with 1=0 where clause returns nothing with the enablefields.
Related
How can I convert below SQL to lambda or LINQ?
with cte
as (select * from test1
union all
select * from test2)
select * from cte
union all
select sum(columnA),sum(columnB),sum(columnC) from cte
In Linq UNION ALL is .Concat(), so:
var cte = test1.Concat(test2);
var sums = new MyModel
{
columnA = cte.Sum(c => c.columnA),
columnB = cte.Sum(c => c.columnB),
columnC = cte.Sum(c => c.columnC),
}
return cte.Concat(IEnumerable.Repeat(sums, 1));
You must remember that test1 and test2 must be type MyModel and MyModel contains only columnA, columnB and columnC.
I put two tables together in one datagridvie but in the last row of datagridview I need the total for both tables in the country, I can do one row in total for one table and another row for the other table I also don't need it, like I can only have one line with the total of both tables.
DataContex db = new DataContex();
var query = (
from v1 in db.View1
where shf.Date >= dpDate.Value && shf.Date <= dpDate1.Value
select new
{
v1.Name,
v1.Date,
v1.Quality,
v1.Rat,
v1.Total
}
).Concat
(
from v2 in db.View2
where f.Date >= dpDate.Value && f.Date <= dpDate1.Value
select new
{
v2.Name,
v2.Date,
v2.Quality,
v2.Rat,
v2.Total
}
).Concat
(from View2 in
(from v2 in db.View2
where v2.Date >= dpDate.Value && sh.Date <= dpDate1.Value
select new
{
v2.Name,
v2.Date,
v2.Quality,
v2.Rate,
v2.Total
})
group v2 by new { v2.NRFA } into g
select new
{
Name = "Total:",
Date = dpDate1.Value,
Quality = (decimal?)g.Sum(p => p.Quality),
Rate = (decimal?)g.Sum(p => p.Rate),
Total = (decimal?)g.Sum(p => p.Total)
}
);
Blockquote
I have two tables: products and current_product_attribute_values
I have tried a join query to filter them as per attribute selected by the user but when I try this with an additional condition it gives me 2 results instead of one it is including the first one which is not matching as per query:
select * from `products` inner join `current_product_attribute_values` on `products`.`id` = `current_product_attribute_values`.`product_id` where `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `product_name` LIKE ?
here is my laravel Controller code :
$all = Input::all();
$q = Input::get('search_text');
$att_val = Input::get('attribute_value');
$subcat = Input::get('subcat_id');
$subcat_name = DB::table('subcategories')->where('id', $subcat)->value('subcategory_name');
$brandname = DB::table('brands')->where('subcat_id', $subcat)->value('brand_name');
$brand_id = DB::table('brands')->where('subcat_id', $subcat)->value('id');
$product_count = DB::table('products')->where('brand_id', $brand_id)->count();
if ($q != "") {
// getting multiple same name params
$query = DB::table('products');
$query->join('current_product_attribute_values', 'products.id', '=', 'current_product_attribute_values.product_id');
$j = 0;
foreach ($all as $key => $values) {
//echo 'my current get key is : ' . urldecode($key). '<br>';
if ($key == $name[$j]) {
$query->where('current_product_attribute_values.attribute_id', '=', $att_id_value[$j]);
echo'<br>';
print_r($query->toSql());
echo'<br>';
//echo '<br> key matched and have some value : <br>';
//echo count($values);
if (count($values) >= 1) {
//echo '<br> it has array inside <br>';
foreach ($values as $val) {
// or waali query in same attribute
echo'<br>';
$query->orwhere('current_product_attribute_values.attribute_value_id', '=', $val);
print_r($query->toSql());
echo'<br>';
}
}
$j++;
}
}
$records = $query->toSql();
$query->where('product_name', 'LIKE', '%' . $q . '%');
$records = $query->toSql();
print_r($records);
$products = $query->paginate(10)->setPath('');
$pagination = $products->appends(array(
'q' => Input::get('q')
));
if (count($products) > 0) {
$filters = DB::table('product_attributes')->where('subcategory_id', $subcat)->get(['attribute_title']);
} else {
$filters = array();
}
$categories = categories::where('add_to_menu', 1)->with('subcategories')->with('brands')->get();
$categoryhome = categories::where('add_to_menu', 1)->with('subcategories')->get();
return view('searchfilter')
->with('productsdata', $products)
->with('filtersdata', $filters)
->with('categories', $categories)
->with('categorieshome', $categoryhome)
->with('subcat_name', $subcat_name)
->with('subcat_id', $subcat)
->with('brandname', $brandname)
->with('product_count', $product_count)
->with('querytext', $q);
}
return 'No Details found. Try to search again !';
its easier if you use raw sql as calling db select function. ex:
$query=DB::select("select * from `products` inner join `current_product_attribute_values` on `products`.`id` = `current_product_attribute_values`.`product_id` where `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `product_name` LIKE ?
");
indeed you can concat vars in raw sql if you need to, ex:
$queryBrands = "select id from brands where subcat_id =".$subcat;
//echo $queryBrands
$queryBrands = DB::select($queryBrands);
By looking at your tables, product table with id value 17 has two records in table current_product_attribute_values in column product_id (I assume this column is used as foreign key to product table).
With select *, you select all of the columns from both tables. So it would most likely cause your query to return multiple records.
My suggestions:
Only select the columns you need. Avoid using select * in the long run, i.e. select product.id, product.description, current_product_attribute_values.attribute_values ......
Make use of GROUP BY
Hope these helps.
I hope some kind person can help me out here.
I want to sort nested comments in wordpress by likes. I have only found one plugin that does this and it doesn't meet my needs, so I'm attempting to write my own. Most of it is actually pretty straightforward, but the sql is eluding me (not really my strength).
I need an SQL Query to sort comments by likes, with replies immediately following their parent, and replies to each parent also sorted by likes. Top level comments and replies are differentiated by 'layer'. There is only one level of replies. My table looks like this:
ID (Int)
Comment_Name (VarChar)
Layer (Int)... 1 for top level comment, 2 for reply
ID_of_Parent_Comment (Int)... replys must be grouped under top level comment with this id
Likes (Int)
For example, if top level comments are represented by numbers and replies by letters, it would look something like this:
1, 2, 3, 3a, 3b, 4, 5, 5a... etc
Anyone have any ideas?
It turns out that the other answer did not quite work out after all. It sure looked right. Replies were grouped nicely beneath the appropriate parent comment, everthing was sorted by likes. But if you look closely, the sqlfiddle test returned 14 records where there are only 12 available.
After spending way too much time fiddling with it on my site, I couldn't resolve it any further. One group or the other (top level comments or replies) were always either left off or duplicated.
I finally gave up, assuming that it could not be done with SQL, so I went back to something I was familiar with: php. Here is my solution. Hopefully someone will find it useful. If nothing else, it was a fun project.
myComments.php
<?php
global $wpdb;
$post_ID = get_the_ID();
// Get Comment Table
$sql =
" SELECT *"
." FROM wp_comments"
." WHERE comment_post_ID = " . $post_ID // only retrieve comments for this post
." AND comment_parent = '0'" // only retrieve top level comments
." ORDER BY likes DESC"
.";";
$tlc = $wpdb->get_results($sql, ARRAY_A); // Retrieve all records into $tlc
// this should never be
// large enough to be a problem.
$commentCount = count( $tlc ); // Number of TopLevelComments
// Adjust Comments
for ( $i = 0; $i <= $commentCount-1; $i++ ) {
$tlc[$i]['layer'] = 0; // Layer 0 indicates top level comment
$tlc[$i]['index'] = $i; // index is used to group parents
// with children
}
// Get Reply Table
$sql =
" SELECT *"
." FROM wp_comments"
." WHERE comment_post_ID = " . $post_ID
." AND comment_parent > '0'" // only retrieve replies
." ORDER BY likes DESC"
.";";
$replies = $wpdb->get_results($sql, ARRAY_A);
$replyCount = count( $replies );
// Adjust Replies
for ( $i = 0; $i <= $commentCount-1; $i++ ) {
$replies[$i]['layer'] = 1; // Layer 1 indicates replies
}
// Set child index to that of parent
// then add child record to parent array
for ( $i = 0; $i <= $replyCount-1; $i++ ) {
$x = $replies[$i]['comment_parent']; // Get ID of parent
for ( $j = 0; $j <= $commentCount-1; $j++ ) {
if ( $tlc[$j]['comment_ID'] == $x ) { // If parent found
$value = $tlc[$j]['index']; // Get parent's index
$replies[$i]['index'] = $value; // Give child parent's index
array_push ( $tlc, $replies[$i]);
}
}
}
// Sort comments
// Note that $tlc was sorted by select
// and index was assigned while in that order
$tlc = array_orderby($tlc, 'index', SORT_ASC,
'layer', SORT_ASC,
'likes', SORT_DESC);
// Display comments
$commentCount = count($tlc);
if ( $commentCount ) {
echo "<ol class='commentNumbering'>";
// Used to determine if we have opened a second <ol> for nested comments
// and ensure we close it before we are done.
$inReplyList = false;
// We don't want to close the <ol> before we've opened it.
$firstComment = true;
for ( $i = 0; $i <= $commentCount-1; $i++ ) {
$myComment = $tlc[$i];
// Set $depth (needed by reply-link on myCommentTemplate page)
$depth = 0;
$comment_ID = $myComment['comment_ID'];
while( $comment_ID > 0 ) {
$tempComment = get_comment( $comment_ID );
$comment_ID = $tempComment->comment_parent;
$depth++;
}
// Treat each group of nested comments as a separate ordered group
if ( $depth == 2 ) {
if ( ! $inReplyList ) {
echo "<ol>";
$inReplyList = true;
}
} else {
if ( ! $firstComment ) {
if ( $inReplyList ) {
echo "</ol>";
$inReplyList = false;
}
}
}
$firstComment = false;
// Display each comment
include ('myCommentTemplate.php');
}
if ( $inReplyList ) {
echo "</ol>";
}
echo "</ol>";
} else {
echo 'No comments found.';
}
// Where comments are made
include('myCommentForm.php');
$wpdb->flush();
?>
function array_orderby() (located in functions.php)
/* SORT PHP ARRAYS OF RECORDS */
// PHP function 'array_multisort' requires columns //
// This function handles the conversion from row to col and back again //
// Example:
// $sorted = array_orderby($data, 'volume', SORT_DESC, 'edition', SORT_ASC);
function array_orderby()
{
$args = func_get_args();
$data = array_shift($args);
foreach ($args as $n => $field) {
if (is_string($field)) {
$tmp = array();
foreach ($data as $key => $row)
$tmp[$key] = $row[$field];
$args[$n] = $tmp;
}
}
$args[] = &$data;
call_user_func_array('array_multisort', $args);
return array_pop($args);
}
Looks like this should be close:
select
post.ID,
post.likes as postLikes,
reply.ID,
reply.likes as replyLikes
from MyTable post
left join MyTable reply
on post.ID = reply.ID_of_Parent_Comment
where post.ID_of_Parent_Comment is null
order by post.likes desc, reply.likes desc
;
It will give you the parent ID's sorted by parent likes and the related child ID's for each parent (if any) sorted by most liked child
I am a newbie intern way over my head, I promise I have researched this thoroughly and tried many different things. The following linq query works, but I want to group rows by last and first name and then only show the rows that appear more than once. When I un-comment out the group by statement, all my aliases below become unrecognized and changing them to the actual db.table names doesn't help.
var query = from emps in db.Employees
join c in db.Cards on emps.SbiID equals c.SbiID
where c.StateID == 0 && c.CardNumberNumeric > 100000
//group emps by new {emps.Surname, emps.Name};
//orderby grp.Count() // something like 'where grp.Count > 1
select new
{
Surname = emps.Surname,
Name = emps.Name,
CorpID = emps.Identifier,
CardNum = c.CardNumber,
CostCenter = emps.EmployeeUserField.UF13,
Supervisor = (from e in db.Employees
where
e.Identifier.Equals(emps.EmployeeUserField.UF5)
select e.Surname).FirstOrDefault()
+ ", "
+ (from e in db.Employees
where e.Identifier.Equals(emps.EmployeeUserField.UF5)
select e.Name).FirstOrDefault(),
SupervisorID = emps.EmployeeUserField.UF5,
EmpCommence = emps.CommencementDateTime,
CardCommence = c.CommencementDateTime,
WorkPhone = emps.Telephone,
State = (from cf in db.ComboFields
from sp in db.StringProperties
where cf.ComboIndex.Equals(c.StateID)
&& cf.StringID.Equals(sp.StringID)
&& cf.TableName.Equals("Card")
&& cf.FieldName.Equals("StateID")
select sp.DefaultValue).FirstOrDefault()
};
this.tagsGridView.DataSource = query;
this.tagsGridView.DataBind();
I think the problem you're running into is that you're not flattening out your groups appropriately. For example:
var duplicateEmployees = db.Employees
.GroupBy(emp => emp, new EmployeeComparer())
.Where(grp => grp.Count() > 1)
.SelectMany(grp => grp.AsEnumerable());
var duplicateEmployeeInfo =
from emps in duplicateEmployees
join c in db.Cards on emps.SbiID equals c.SbiID
where c.StateID == 0 && c.CardNumberNumeric > 100000
select new
{
... what to select
};
With:
public class EmployeeComparer : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
return x.Surname == y.Surname && x.Name == y.Name;
}
public int GetHashCode(Employee obj)
{
unchecked { return (17 * obj.Surname.GetHashCode()) ^ (23 * obj.Name.GetHashCode()); }
}
}
This groups the employees by name, finds the groups that have a count > 1, then returns the elements of those groups. No guarantees on performance, but this should solve your issue.
below are the table structures according to which I have to develop the desired output(given at the end)
tbl_docatr
docatr_id doc_id docatrtype_id docatr_float docatr_int docatr_date docatr_varchar docatr_blob
1 12 1 NULL NULL NULL testing [BLOB - NULL]
2 12 2 NULL NULL NULL Tesitng [BLOB - NULL]
tbl_docatrtype
docatrtype_id docatrtypegroup_id docatrtypetype_id docatrtype_name
1 1 4 Name
2 1 4 Company Name
tbl_docatrtypetype
docatrtypetype_id docatrtypetype_name
1 Float
2 Int
3 Date
4 String line
Above are three tables from which I have to display the desired output as
Name : testing
Company Name : Tesitng
such that at first step I have doc_id then I get docatrtype_id and then docatrtypetype_id acording to these values i have to fetch the result. Also the query must see the doactrtypetype_id from table tbl_docatrtypetype and fetch the result from tbl_docatr from respective column docatr_float, docatr_int, docatr_date, docatr_varchar, docatr_blob
UPDATE
I Have created the below PHP functions for the queries please help me to get the easy one
function getDocumentDetail($doc_id){
$arr_document_detail = array();
$query = "SELECT * FROM tbl_doc WHERE doc_id = '".$doc_id."'";
$this->connect->executeQuery($query, $this->connect->conn);
if($this->connect->numRows() > 0) {
while($row = $this->connect->getRowArr()){
$arr_document_detail = $row;
}
}
return $arr_document_detail;
}
//Getting Attribute Details
function getAttributeDetails($doc_id){
$arr_attrtype_id = array();
$query = "SELECT
docatrtype_id,
docatr_float,
docatr_int,
docatr_varchar,
docatr_date,
docatr_blob
FROM
tbl_docatr
WHERE
doc_id = '".$doc_id."'";
$this->connect->executeQuery($query, $this->connect->conn);
if($this->connect->numRows() > 0){
$j = 0;
while($row1 = $this->connect->getRowArr()){
$arr_attrtype_id[$j] =$row1;
$j++;
}
}
return $arr_attrtype_id;
}
function getAttrTypetype($attrtype_id){
$arr_attrtypetype = array();
$query = "SELECT
docatrtype_name,
docatrtype_id,
docatrtypegroup_id,
docatrtypetype_id
FROM
tbl_docatrtype
WHERE
docatrtype_id = '".$attrtype_id."'";
$this->connect->executeQuery($query, $this->connect->conn);
if($this->connect->numRows() > 0){
$i = 0;
while($row1 = $this->connect->getRowArr()){
$arr_attrtypetype[$i] =$row1;
$i++;
}
}
return $arr_attrtypetype;
}
function getAttrtypetypedetail($attrtypetype_id){
$arr_attrtypetype_detail = array();
$query = "SELECT
docatrtypetype_name,
docatrtypetype_id
FROM
tbl_docatrtypetype
WHERE
docatrtypetype_id = '".$attrtypetype_id."'";
$this->connect->executeQuery($query, $this->connect->conn);
if($this->connect->numRows() > 0){
$i = 0;
while($row1 = $this->connect->getRowArr()){
$arr_attrtypetype_detail[$i] =$row1;
$i++;
}
}
return $arr_attrtypetype_detail;
}
UPDATE--2 as per #Danosaure
select concat(dat.docatrtype_name, ':',
case dat.docatrtypetype_id
when '1' then da.docatr_float
when '2' then da.docatr_int
when '3' then da.docatr_date
when '4' then da.docatr_varchar
when '5' then da.docatr_blob
end) as 'Value'
from tbl_docatr da
inner join tbl_docatrtype dat using (docatrtype_id)
inner join tbl_docatrtypetype datt using (docatrtypetype_id)
WHERE da.doc_id=33
ORDER BY da.docatr_id;
For the sake of "integrity", you should add a (5, 'Blob') row to tbl_docatrtypetype.
select dat.docatrtype_name,
case datt.docatrtypetype_name
when 'Float' then da.docatr_float
when 'Int' then da.docatr_int
when 'Date' then da.docatr_date
when 'String line' then da.docatr_varchar
else da.docatr_blob
end as 'Value'
from tbl_docatr da
inner join tbl_docatrtype dat using (docatrtype_id)
inner join tbl_docatrtypetype datt using (docatrtypetype_id)
WHERE da.doc_id=12
ORDER BY da.docatr_id;
EDIT: Added doc_id specific values per OP comment.