I need to run a query like below
SELECT `loginname`, `id`, `locality`, `wherefrom`
FROM `Volley` JOIN `register` ON loginname=username
WHERE CONCAT_WS('', wherefrom,locality) LIKE '%$search%'
from this result i need to take id and pass it to the other query to check that id exist in another table like below.
SELECT IF(EXISTS(SELECT *
FROM `likes`
WHERE Volleyid = '20'),1,0)
Can i combine this into a single query? For the first one i may get more that 1 rows. I tried and got the results of first query into a array but i am not able to get that particular value from array.
$data = array();
for ($x = 0; $x < mysqli_num_rows($query1); $x++)
{
$data[] = mysqli_fetch_assoc($query1);
}
SELECT IF(EXISTS(SELECT * From
(
SELECT `loginname`,
`id`,
`locality`,
`wherefrom`,
Volleyid
FROM `Volley`
JOIN `register`
ON loginname=username
WHERE CONCAT_WS('', wherefrom,locality) LIKE '%$search%'
) AS T1
WHERE Volleyid = '20'),1,0)
You can use a subquery with IN clause (i think what you what it ś that Volleyid it's equal to id):
SELECT IF(EXISTS(SELECT *
FROM `likes`
WHERE Volleyid IN
(SELECT `id`
FROM `Volley` JOIN `register` ON loginname=username
WHERE CONCAT_WS('', wherefrom,locality) LIKE '%$search%')),1,0)
If you want to get loginname, id, locality, wherefrom columns in the first query alongside with the 1 or 0 flag checked against table likes in single result set. You can write query that looks like this:
SELECT v.*, IF(l.Volleyid IS NOT NULL, 1, 0) as existFlag
FROM
(SELECT `loginname`, `id`, `locality`, `wherefrom`
FROM `Volley`
JOIN `register` ON loginname=username
WHERE CONCAT_WS('', wherefrom,locality) LIKE '%$search%') AS v
LEFT JOIN
(SELECT DISTINCT Volleyid
FROM `likes`) l ON v.id = l.Volleyid;
Related
What I'm trying to do here, is I want to output the count of the id and user_id columns from items, by users which have the rank 1.
Let's say there's 8 rows in items which have a base_item of 400, and these 8 rows, where 2 rows of them has a user_id of 4 and the existing left has a user_id of 6 The output should then be:
$countItems = 8 and $countUsers = 2.
$stmt = $conn->pdo->prepare("
SELECT COUNT(*),`user_id` FROM `items`
INNER JOIN `users`
ON `users`.`id` = `items`.`user_id`
WHERE `base_item` = :i AND `rank` = 1
GROUP BY `user_id`,`items`.`id`
");
$data = array(':i' => '400'); // item_id in `values` table
$stmt->execute($data);
if($inv = $stmt->fetch($db->FETCH_ASSOC)) {
$countItems = $inv['id'];
$countUsers = $inv['user_id'];
}
I have tried several methods, but I still keep getting output 2 and 2 even though the results should be 8 and 2.
Table Info for values:
Table Info for items:
First of all you never want to fetchAll() and discard the data just to count the number of rows. There is a better way.
SELECT COUNT(*) FROM `items` WHERE `base_item` = :item AND `user_id` = :uid
Secondly, you should try to avoid a nested loop whenever possible because nested loops don't scale very well. And the solution is to use a join or a subquery. You haven't posted your table structures, so this query is untested.
SELECT COUNT(*), user_id FROM `items` INNER JOIN users
ON users.id = items.user_id
WHERE `base_item` = :item and rank =1 GROUP BY user_id
One query instead of two, a lot less number of lines of code.
Problem is that you're replacing $smst withing the foreach loop.
Use other variable name, for example:
$stmt->execute();
foreach($stmt as $user) {
$stmt2 = $conn->pdo->prepare("SELECT `id`,`user_id` FROM `items` WHERE `base_item` = :item AND `user_id` = :uid");
$stmt2->bindParam(':item', $cmsval['item_id'], $db->PARAM_INT);
$stmt2->bindParam(':uid', $user['id'], $db->PARAM_INT);
Well, all I actually had to do, was remove GROUP BY and add COUNT DISTINCT instead, like following:
$stmt = $conn->pdo->prepare("
SELECT COUNT(DISTINCT `user_id`) as `uid`,
COUNT(`items`.`id`) as `id`
FROM `items`
INNER JOIN `users`
ON `users`.`id` = `items`.`user_id`
WHERE `base_item` = :i AND `rank` = 1
");
$stmt->bindParam(':i', $cmsval['item_id'], $db->PARAM_INT);
$stmt->execute();
if($inv = $stmt->fetch($db->FETCH_ASSOC)) {
$countItems = $inv['id'];
$countUsers = $inv['uid'];
}
I have table where I store data on basis of date.
Now I need to check that: is there any difference between data of rows with two different dates.
In a simple way you can say that I have two queries which select data from same table now I have to compare each row and column value. for example my two query are -
SELECT * FROM `national` WHERE `upload_date` = '2015-08-04' // return 106 rows
and
SELECT * FROM `national` WHERE `upload_date` = '2015-08-01' // return 106 rows
I have tried to compare this with below query but the result not seem to be correct to me, I am not satisfy with this.
Select U.* from
(SELECT t1.* FROM `national` t1 where upload_date = '2015-08-01'
union all
SELECT t2.* FROM `national` t2 WHERE `upload_date` = '2015-08-04' ) U
GROUP BY emp_id, uqi_id
HAVING COUNT(*) = 1
Can Any one please provide me correct query ?? thank you
Try this
(
SELECT t1.*
FROM
`national` t1, `national` t2
where
t1.upload_date = '2015-08-01' and t2.upload_date='2015-08-04' and
-- put your columns here that you want to compare for same DATA
-- like t1.name=t2.name and etc...
)
You can try with something like that
SELECT * FROM (SELECT * FROM `national` WHERE upload_date = '2015-08-01') a
INNER JOIN (SELECT * FROM `national` WHERE upload_date = '2015-08-04') b
ON a.emp_id = b.emp_id AND a.uqi_id = b.uqi_id
ORDER BY uqi_id
I want to show only that data which date is null
Here is my query:
$Query = "SELECT att.`EmployeeCode`,emp.FullName ,emp.EmployeeID,emp.Photo,sum(TIME_TO_SEC(att.FinalTime)/60 - IFNULL(sp.TotalTimeLateMark,$TotalTimeLateMark)) OverTime
FROM `hr_tblattendancehistory` att
left join hr_tblemployee emp on att.EmployeeCode = emp.CardID
left join hr_tblspecialattendancesetting sp on sp.Date = att.Date
WHERE emp.FullName!='' and att.`Date` Between '$FromDate' and '$Todate=''' and (TIME_TO_SEC(att.FinalTime)/60 -IFNULL(sp.TotalTimeLateMark,$TotalTimeLateMark)) > 0
group by att.`EmployeeCode`,emp.Photo,emp.FullName
order by SUM(TIME_TO_SEC(att.FinalTime)/60 -IFNULL(sp.TotalTimeLateMark,$TotalTimeLateMark)) DESC";
How can I do this ?
You can use IS NULL
e.g.
SELECT * FROM YourTable WHERE DateColumn IS NULL;
In your particular case you are probably looking for IS NULL, just like Nilesh Thakkar has pointed out. But in the HAVING clause:
SELECT * FROM YourTable A
LEFT JOIN AnotherTable B on A.DateColumn=B.DateColumn
HAVING DateColumn IS NULL;
That is because the selection should happen after the join, not before.
Is it possible to do something like this:
SELECT *,
COUNT(* WHERE media_id = 1) as count_1,
COUNT(* WHERE media_id = 2) as count_2
WHERE user_id = 1
or do I have to make separate queries?
Thanks.
You can use conditional sum something as
select
sum(media_id = 1) as count_1,
sum(media_id = 2) as count_2
from table_name
where user_id = 1;
Note that using aggregate function does not make sense with select *
Yup, it's possible.
Try this for example:
select
(select count(*) from TableA where 1=1) as totalA,
(select count(*) from TableB where 1=1) as totalB,
(select count(*) from TableC where 1=1) as totalc
I need to get data from a table using this query:
(select columns
from tableX
join tableZ
on tableX.id1 = tableZ.other_id)
union all
(select columns
from tableX
join tableZ
on tableX.id2 = tableZ.other_id)
LIMIT num1, num2
Without the LIMIT, I get the correct result with my query builder that look like this (let $first be the first query of select and $second is the other select query):
$first->unionAll($second)->get();
When I try to put skip and/or take, the result is not the same as the first query above.
$first->unionAll($second)->take(num1)->skip(num2)->get();
The result query from the above builder (I got it from DB::getQueryLog()) is something like:
(select columns
from tableX
join tableZ
on tableX.id1 = tableZ.other_id LIMIT num1, num2)
union all
(select columns
from tableX
join tableZ
on tableX.id2 = tableZ.other_id)
which ofcourse yield incorrect result. Does anyone knows what is the work around to make the first query? Thanks!
You need to wrap $firstQuery in another query, like this:
$first->unionAll($second);
$rows = DB::table( DB::raw("({$first->toSql()}) as t") )
->mergeBindings($first->getQuery())
->take(num1)->skip(num2)
->get();
This will result in the following query:
select * from (FIRST_QUERY union all SECOND_QUERY) as t limit num1, num2
One Workaround is to use raw query using DB::select and DB::raw in below sample block...
$num1 = 100; // skip first 100 rows
$num2 = 2; // take only 2 rows
$qry_result = DB::select(DB::raw("select * from
(
(select columns from tableX join tableZ on tableX.id1 = tableZ.other_id)
union all
(select columns from tableX join tableZ on tableX.id2 = tableZ.other_id)
) Qry LIMIT :vskip , :vlimit ") , array('vskip'=>$num1,'vlimit'=>$num2)
);