I have following sql JOIN query:
public function exportAll($date) {
$sql = "SELECT CONCAT(u.firstname, u.lastname) as fullname, c.early_checkout_remarks, c.delayed_checkin_remarks, DATE(c.checkin_time) as checkin_date, DATE(c.checkout_time) as checkout_date, TIME(c.checkin_time) as checkin_time, TIME(c.checkout_time) as checkout_time
FROM users u
LEFT JOIN checkin_checkout c
ON u.id=c.users_id
AND (DATE(c.checkin_time) = '%s' OR DATE(c.checkout_time) = '%s')
AND u.deleted IS NULL
ORDER BY fullname,checkin_date";
$records = $this->db->exec(sprintf($sql,$date,$date));
return $records;
I only want records of users who are not deleted. But this query is also returning users with values in 'deleted' column.
For that I think you need to move
AND u.deleted IS NULL
into a WHERE clause. Currently that AND is applied to the join only, not to the final result. And since it's a LEFT join, it doesn't fully restrict the results.
Try:
SELECT
CONCAT(u.firstname, u.lastname) as fullname,
c.early_checkout_remarks,
c.delayed_checkin_remarks,
DATE(c.checkin_time) as checkin_date,
DATE(c.checkout_time) as checkout_date,
TIME(c.checkin_time) as checkin_time,
TIME(c.checkout_time) as checkout_time
FROM
users u
LEFT JOIN
checkin_checkout c
ON u.id = c.users_id
AND (DATE(c.checkin_time) = '%s' OR DATE(c.checkout_time) = '%s')
WHERE
u.deleted IS NULL
ORDER BY
fullname,
checkin_date
It's not clear from your question where the part about check-in dates should also be in the where clause. We'd need to know more about the requirements and your data structure. But it's something you can try if you need to.
Note also I reformatted your query - I (personally) find queries formatted like this can be read and understood a lot faster and more accurately. It's easier to see what is being done where, and what applies to what.
$sql = "SELECT CONCAT(u.firstname, u.lastname) as fullname, c.early_checkout_remarks, c.delayed_checkin_remarks, DATE(c.checkin_time) as checkin_date, DATE(c.checkout_time) as checkout_date, TIME(c.checkin_time) as checkin_time, TIME(c.checkout_time) as checkout_time
FROM users u
LEFT JOIN checkin_checkout c ON u.id=c.users_id
WHERE (DATE(c.checkin_time) = '%s' OR DATE(c.checkout_time) = '%s')
AND u.deleted IS NULL
ORDER BY fullname,checkin_date";
$records = $this->db->exec(sprintf($sql,$date,$date));
return $records;
WHERE added after the JOIN. You can use with ON as well.
Try below query.
SELECT CONCAT(u.firstname, u.lastname) as fullname, c.early_checkout_remarks, c.delayed_checkin_remarks, DATE(c.checkin_time) as checkin_date, DATE(c.checkout_time) as checkout_date, TIME(c.checkin_time) as checkin_time, TIME(c.checkout_time) as checkout_time
FROM users u
LEFT JOIN checkin_checkout c
ON u.id=c.users_id
Where (DATE(c.checkin_time) = '%s' OR DATE(c.checkout_time) = '%s')
AND u.deleted IS NULL
ORDER BY fullname,checkin_date
Related
Here is database table:
$sql[2] = "SELECT u.* , oi.* , COUNT(oi.user_id) AS count
FROM users u, order_items oi
WHERE u.id=oi.user_id ";
$result3= mysqli_query($conn,$sql[2]) or die(mysqli_error());
if (mysqli_num_rows($result3) > 0) {
while ($record = mysqli_fetch_array($result3)) {
echo $record['count'];
}
}
I want to count how much order have every user. Example: Like Thomas have 3 order, but my code is writing 4, i want to write Thomas (3), Gracian(1). Any idea how to fix it ?
Use this query:
SELECT u.id,
COUNT(oi.user_id) AS orderCount
FROM users u
LEFT JOIN order_items oi
ON u.id = oi.user_id
GROUP BY u.id
The reason we count user_id from the order_items table is because of the edge case where a given user has no orders. In this case, we want to make sure that his count would appear as zero. The COUNT function ignores NULLs, which is what we want.
There is another way to perform the sql query using subqueries:
SELECT id,
email,
address,
name,
(SELECT count(user_id) FROM order_items WHERE user_id = users.id) AS orderCount FROM users;
i need help getting data from different tables and insert into other different table Here are the Queries
"SELECT commentID, date, comment, subject, parentID, aBUserID FROM comments WHERE status = 'APPROVED'"
"SELECT topicID, subForumID, aBUserID, lastPostID, views, replies, startDate FROM topic WHERE status = 'APPROVED' AND topicID = $parentid";
// $parentID need to be matched from above query parentID,
"SELECT userName FROM users WHERE aBUserID = $cmtaBUserID";
// $cmtaBUserID = aBUserID from first query
"SELECT userName FROM users WHERE aBUserID = $topicaBUserID";
//$topicaBUserID = aBUserID from second query
Last 2 queries are from same table but using different where clause
i used different inner join left join from solutions posted here but non of these worked for me stuck since last 2 weeks please help
PS data from all above Queries will be inserted to a single table i need these to be combined so i can have them all in one place
If you want to perform the operation in same query use 'OR'
"SELECT userName FROM users WHERE aBUserID = $cmtaBUserID OR aBUserID = $topicaBUserID";
Please try this
SELECT userName from users where aBUserID IN(SELECT aBUserID FROM comments WHERE status = 'APPROVED')
Couldn't test it but Maybe this is what you are looking for.
SELECT c.commentID, c.date, c.comment, c.subject, c.parentID, c.aBUserID,
t.topicID, t.subForumID, t.aBUserID, t.lastPostID, t.views, t.replies, t.startDate,
u.userName
FROM
comments c
left outer join topic t on t.topicID = c.parentID
left outer join users u on u.aBUserID = c.aBUserID and u.aBUserID = t.aBUserID
WHERE
c.status = 'APPROVED' and t.status = 'APPROVED';
try this:
SELECT
comment.[commentID],
comment.[date],
comment.[comment],
comment.[subject],
comment.[parentID],
comment.[aBUserID],
commentuser.[userName],
topic.[topicID],
topic.[subForumID],
topic.[aBUserID],
topic.[lastPostID],
topic.[views],
topic.[replies],
topic.[startDate],
topic.[userName]
FROM comments comment
LEFT OUTER JOIN users commentuser
ON commentuser.aBUserID = comment.[aBUserID]
LEFT OUTER JOIN
(
SELECT
t.[topicID],
t.[subForumID],
t.[aBUserID],
t.[lastPostID],
t.[views],
t.[replies],
t.[startDate],
u2.[userName] --user from users table joined to topics table
FROM topic t
LEFT OUTER JOIN users u
ON u.aBUserID = t.[aBUserID]
WHERE t.[status] = 'APPROVED'
) topic
ON topic.topicID = comment.parentID
WHERE comment.[status] = 'APPROVED'
The following statement gets row counts for user_ids from various tables/conditions where the users are within specific computers of a specific account. It works as expected. An example output would be something like this :
Array
(
[0] => Array
(
[computer_name] => COMPUTER_1
[username] => Steve
[t1count] => 13
[t2count] =>
[t3count] => 23
[t4count] => 64
)
... and so on for each
the statement :
$stmt = $db->prepare("
SELECT c.computer_name, users.username, t1count, t2count, t3count, t4count
FROM
( SELECT account_id, computer_id, computer_name
FROM computers
WHERE account_id = ".$_SESSION['user']['account_id']."
ORDER BY computer_id ASC LIMIT 0, ".$_SESSION['user']['licenses']."
) as c
LEFT JOIN users
on users.computer_id = c.computer_id
LEFT JOIN
(SELECT user_id, COUNT(user_id) as t1count
FROM t1
WHERE t1.title LIKE 'started'
GROUP BY user_id) as t_t1
on t_t1.user_id = users.user_id
LEFT JOIN
(SELECT user_id, COUNT(user_id) as t2count
FROM t2
GROUP BY user_id) as t_t2
on t_t2.user_id = users.user_id
LEFT JOIN
(SELECT user_id, COUNT(user_id) as t3count
FROM t1
WHERE t1.title LIKE 'blocked'
GROUP BY user_id) as t_t3
on t_t3.user_id = users.user_id
LEFT JOIN
(SELECT user_id, COUNT(user_id) as t4count
FROM t1
WHERE t1.title LIKE 'closed'
GROUP BY user_id) as t_t4
on t_t4.user_id = users.user_id
... and so on for each
WHERE c.account_id = ?
");
I want to also return a totalsum = t1count + t2count + t3count + t4count in this statement as well, but can't seem to get anything working. In this situation I cannot do outside processing (adding the values that are returned)... it needs to be in the statement. I am also open to any suggestions in what I already have if there are better options.
What are you trying to do with these values? SUM(t1count,t2count,t3count,t4count) AS totalsum should work to get a count of counts.
Your query is a bit hard to read. You have implicit and explicit JOINs. You are grouping numerous times and pulling columns when you can generally do this all in one shot. If you share an SQLFiddle, I will be able to clean this up, but in short:
SELECT
c.computer_name,
users.username,
count(t_t1.user_id) AS t1count,
count(t_t2.user_id) AS t2count,
count(t_t3.user_id) AS t3count,
count(t_t4.user_id) AS t4count,
(count(t_t1.user_id)+count(t_t2.user_id)+count(t_t3.user_id)+count(t_t4.user_id)) AS totalsum FROM users
LEFT JOIN computers AS c ON users.computer_id=c.computer_id AND c.account_id=?
LEFT JOIN t1 AS t_t1 ON t_t1.user_id = users.user_id AND t_t1.title LIKE "started"
LEFT JOIN t2 AS t_t2 ON t_t2.user_id = users.user_id
LEFT JOIN t1 AS t_t3 ON t_t3.user_id = users.user_id AND t_t3.title LIKE 'blocked'
LEFT JOIN t1 AS t_t4 ON t_t4.user_id = users.user_id AND t_t4.title LIKE 'closed'
WHERE c.account_id = ?
AND t_t1.title LIKE started
GROUP BY users.user_id;
This may need tweaking, as I stated, but it is a lot cleaner and easier to read and should accomplish something very similar.
Alternately, if you can't get the query to run the way you want it to when you change it to entirely explicit joins, rather than using SUM, try adding the values together like I did in the example above. It should prevent them from aggregating in the same way.
EDIT
After viewing your SQLFiddle, I have doctored up a solution which does away with nested queries. The positive is that it is cleaner. The negative is that it requires you to specify the users using an IN clause.
SELECT computers.account_id,computers.computer_id,computers.computer_name,users.user_id,users.username,count(distinct t_count1.log_id) AS count1,count(distinct t_count2.log_id) AS count2,count(distinct t_count3.log_id) AS count3, count(distinct t_count4.event_id) AS count4,
(count(distinct t_count1.log_id) + count(distinct t_count2.log_id) + count(distinct t_count3.log_id) + count(distinct t_count4.event_id)) AS totalcount
FROM users
INNER JOIN computers ON computers.computer_id=users.computer_id
LEFT JOIN logs AS t_count1 ON t_count1.type LIKE 'type1' AND t_count1.user_id=users.user_id
LEFT JOIN logs AS t_count2 ON t_count2.type LIKE 'type2' AND t_count2.user_id=users.user_id
LEFT JOIN logs AS t_count3 ON t_count3.type LIKE 'type3' AND t_count3.user_id=users.user_id
LEFT JOIN events AS t_count4 ON t_count4.user_id = users.user_id
WHERE computers.account_id=1 AND computers.computer_id in (1,2)
GROUP BY users.user_id
ORDER BY users.user_id ASC,computers.computer_id ASC;
If you choose to keep your current query structure for any reason, adapting it like so should make it work for you:
select *,ifnull(count1,0)+ifnull(count2,0)+ifnull(count3,0)+ifnull(count4,0) AS totalcount from
( select account_id, computer_id, computer_name
from computers
order by computer_id asc limit 0, 2
) as c
left join users
on users.computer_id = c.computer_id
left join
(select user_id, count(user_id) as count1
from logs
where logs.type like 'type1'
group by user_id) as t_count1
on t_count1.user_id = users.user_id
left join
(select user_id, ifnull(count(user_id),0) as count2
from logs
where logs.type like 'type2'
group by user_id) as t_count2
on t_count2.user_id = users.user_id
left join
(select user_id, count(user_id) as count3
from logs
where logs.type like 'type3'
group by user_id) as t_count3
on t_count3.user_id = users.user_id
left join
(select user_id, count(user_id) as count4
from events
group by user_id) as t_count4
on t_count4.user_id = users.user_id
where c.account_id = 1;
My advice would be to follow along each query to understand what you are asking SQL to do. To actually add all values together, you should be counting the number of records that are returned. Counting values of your primary keys helps you to count records. Also, using your other example, ifnull in the second example make sure that null values are not going to interfere with adding. "If a value is null make it 0 instead."
I currently have:
SELECT tbl_review.*, users.first_name, users.last_name, (
SELECT order_ns.tran_date
FROM order_ns
LEFT JOIN product_2_order_ns.external_order_id = order_ns.order_id
WHERE product_2_order_ns.bkfno IN :id
ORDER BY order_ns.trandate ASC
LIMIT 1
) as purchase_date
FROM tbl_review
LEFT JOIN users ON users.sequal_user_id = tbl_review.user_id
WHERE tbl_review.product_id IN :id AND tbl_review.approved = 1
Which, in its sub query, selects an order the user has which has a product in question (defined in :id) get the the oldest transaction date on file for one of the found orders.
I would really like to keep this to one call of the database (don't really want to call again for each returned user for just one field, or even do a range query of all users) but obviously this particular query isn't working.
What can I do, if anything, to get this working?
I cannot make the sub query into a join since they are two distinct pieces of data, the sub query needs to return detail for each row in the main query.
I think you just want a correlated subquery. It is unclear exactly what the relationship is between the inner query and the outer one. My guess is that it is on users and orders:
SELECT tbl_review.*, users.first_name, users.last_name,
(SELECT order_ns.tran_date
FROM order_ns LEFT JOIN
product_2_order_ns
on product_2_order_ns.external_order_id = order_ns.order_id and
product_2_order_ns.bkfno = tbl_review.product_id and
WHERE order_ns.user_id = tbl_review.user_id
ORDER BY order_ns.trandate ASC
LIMIT 1
) as purchase_date
FROM tbl_review LEFT JOIN
users
ON users.sequal_user_id = tbl_review.user_id
WHERE tbl_review.product_id IN :id AND tbl_review.approved = 1;
EDIT:
Oh, the inner query has no relationship to the outer query. Then it is easier. Move it to the from clause using cross join:
SELECT tbl_review.*, users.first_name, users.last_name,
innerquery.tran_date as purchase_date
FROM tbl_review LEFT JOIN
users
ON users.sequal_user_id = tbl_review.user_id cross join
(SELECT order_ns.tran_date
FROM order_ns LEFT JOIN
product_2_order_ns
on product_2_order_ns.external_order_id = order_ns.order_id
WHERE product_2_order_ns.bkfno IN :id
ORDER BY order_ns.trandate ASC
LIMIT 1
) innerquery
WHERE tbl_review.product_id IN :id AND tbl_review.approved = 1;
#Gordons answer is really close but I wanted it to return even if no data was found for tran_date so I changed my query to:
SELECT tbl_review.*, users.first_name, users.last_name, order_ns.tran_date
FROM tbl_review
LEFT JOIN users ON users.sequal_user_id = tbl_review.user_id
LEFT JOIN order_ns ON order_ns.order_id = (
SELECT order_ns.order_id
FROM order_ns
LEFT JOIN product_2_order_ns on product_2_order_ns.external_order_id = order_ns.order_id
WHERE product_2_order_ns.bkfno IN :id
ORDER BY order_ns.tran_date ASC
LIMIT 1
)
WHERE tbl_review.product_id IN :id AND tbl_review.approved = 1;
This will return the distinct data of tran_date irrespective of whether it is found or not.
Let's say I have two tables, users and notes. Let's say the schemas look like this:
users
id, name, field2, field3
notes
id, user_id, subject, heading, body, timestamp
What I want to do is select every user, and the LATEST (just 1) note posted by each user based on the timestamp to show in an overview report.
How would I go about doing this? Please note that the DB is MySQL.
Thanks!
select users.name, notes.subject, notes.heading, notes.body
from users, notes
where users.id = notes.user_id
and notes.timestamp = (select max(timestamp) from notes where user_id = users.id)
select u.id, u.name, n.id as note_id, n.subject, n.heading, n.body, n.timestamp
from users u
left outer join (
select user_id, max(timestamp) as timestamp
from notes
group by user_id
) nm
left outer join notes n on nm.user_id = n.user_id and nm.timestamp = n.timestamp
Note that this could potentially return duplicates if the user has two notes with the exact same timestamp. I have assumed this is not the case.
SELECT *
FROM `users`
LEFT JOIN `notes`
ON `user_id` = `users`.`id`
WHERE `notes`.`timestamp` = (
SELECT MAX(`timestamp`)
FROM `notes` AS `notes_1`
WHERE `notes_1`.`user_id` = `notes`.`user_id`
)