How do I select distinct rows and cross check in another table? - php

I have 3 tables, users and tasks and completed_tasks. So basically I want to select all tasks where the user_id = 2 AND also check that the task does not exist in another table` the So here is my tables:
users table:
+----+-------+
| id | name |
+----+-------+
| 1 | John |
| 2 | Sally |
+----+-------+
tasks table:
+----+-----------+---------+
| id | task_name | user_id |
+----+-----------+---------+
| 1 | mop floor | 2 |
| 2 | dishes | 1 |
| 3 | laundry | 2 |
| 4 | cook | 2 |
+----+-----------+---------+
completed_tasks table:
+----+---------+---------+
| id | task_id | user_id |
+----+---------+---------+
| 1 | 1 | 2 |
+----+---------+---------+
Here is my current SELECT code for my MySQL database:
$db = "SELECT DISTINCT tasks.task_name, users.name FROM tasks LEFT JOIN ON users.id = tasks.user_id WHERE tasks.user_id = 2";
THe problem I'm having is: I want it to search in completed_tasks table and if the task exists, then don't select that task.
I tried to do that by adding the following but it did not work:
LEFT JOIN completed_tasks ON completed_tasks.user_id = 2
That did not work because if I had multiple completed tasks, it would just ignore it all together.
I want the end result should return the user's name and task name of task 3 and 4.
Also, performance is critical in my application. I could use PHP and loop through the arrays and do SELECT for each of them but that would not be good for performance.

You have a few ways to do this.
You can use a LEFT JOIN and then check for NULL in the optional table.
SELECT a.name, b.task_name
FROM users a
JOIN tasks b ON a.id = b.user_id
LEFT JOIN completed_tasks c ON c.task_id = b.id AND c.user_id = b.user_id
WHERE c.id IS NULL
;
You can do a NOT EXISTS sub-query
SELECT a.name, b.task_name
FROM users a
JOIN tasks b ON a.id = b.user_id
WHERE NOT EXISTS (
SELECT 1
FROM completed_tasks c
WHERE c.task_id = b.id AND c.user_id = b.user_id)
;

Related

PDO Query : Count related and repeated values then inner join

I work with PHP and PDO.
So I have 2 tables like,
Table 1
| id | name | age |
| 1 | John | 25 |
| 2 | Tom | 32 |
| 3 | James| 45 |
Table 2
| id | Comment | Link |
| 1 | some text | 3 |
| 2 | some text | 3 |
| 3 | some text | 1 |
So, Link column numbers represent id's in table1. For example Link = 3s in table 2 represent James in table 1. I need a query which brings all table1's data and also a number of repeated value for related Link column which comes from table2.
For example, the query should give me (let's choose James),
| id | name | age | Value |
| 3 | James | 45 | 2 |
value=2, because there are two 3s in link column which related to James
I tried somethings but got lots of errors.
I think you just need the GROUP BY
SELECT a.id,
a.name,
a.age,
count(*) as value
FROM table1 a
JOIN table2 b ON a.id = b.link
GROUP BY a.id, a.name, a.age
If you really want just one row then add WHERE
SELECT a.id,
a.name,
a.age,
count(*) as value
FROM table1 a
JOIN table2 b ON a.id = b.link
WHERE a.name = 'James'
GROUP BY a.id, a.name, a.age
or use subquery
SELECT a.id,
a.name,
a.age,
(SELECT count(*) FROM table2 b WHERE a.id = b.link) as value
FROM table1 a
WHERE a.name = 'James'

Iget data from 1 table and check the data does not exist in second table

I have 3 tables created forum groups and group_members I want to get groups only those which are not in group members along with user id currently it is getting group which group id and user id is not present in the group members table if data is not in the table only if 1 group member exist it pulls up the record . In simple words I want to show show groups which user have not joined here is my table schema for both 3 tables
Groups
+----+----------+
| id | name |
+----+----------+
| 1 | group 1 |
| 2 | group 2 |
| 3 | group 3 |
| 4 | group 4 |
+----+----------+
forums
+------------------+-------------+
| id | title | group_id |
+------------------+-------------+
| 1 | test 1 | 2 |
| 2 | test 2 | 3 |
| 3 | test 3 | 2 |
| 4 | test 4 | 3 |
| 5 | test 5 | 2 |
| 6 | test 6 | 4 |
+------------------+-------------+
Group_members
+-----------------+-------------+
| id | user_id | group_id |
+-----------------+-------------+
| 1 | 107 | 2 |
| 2 | 106 | 3 |
+-----------------+-------------+
Here is my sql I have written
<?php
$sql_grp_chk = $this->db->query("SELECT * FROM groups WHERE NOT EXISTS (SELECT * FROM group_members WHERE groups.id == group_members.group_id)");
foreach($sql_grp_chk->result() as $data_ct):
$sql_gr_coun = $this->db->query("SELECT groups.*, (SELECT count(group_id) FROM forums WHERE groups.id = forums.group_id) as forumcount FROM groups WHERE groups.id != '".$data_ct->id."' ORDER BY forumcount DESC LIMIT 5");
foreach($sql_gr_coun->result() as $data_count):
$sql_follow = $this->db->get_where('group_members', array('group_id' => $data_count->id));
var_dump($data_count);
?>
<?php endforeach; ?>
<?php endforeach; ?>
Not sure why forums is there, but to select all groups that are not linked to a user you can do left join:
select g.* from groups g
left join group_members m on m.group_id = g.id and m.user_id = :userId
where m.id is null;
EDIT:
Select top 5 groups, by number of forums linked:
select g.*, count(nullif(f.id, 1)) as cnt from groups g
inner join forums f on f.group_id = g.id
group by g.id
order by cnt desc
limit 5;
Both queries together - top 5 groups, by number of forums linked, which user has not joined yet:
select g.*, count(nullif(f.id, 1)) as cnt from groups g
left join group_members m on m.group_id = g.id and m.user_id = :userId
left join forums f on f.group_id = g.id
where m.id is null
group by g.id
order by cnt desc
limit 5;

MySQL - inner join - add column with value based on other value

I'm struggling with mysql joins :/
I've multiple tables inside database fe. tasks, users etc.
Table tasks containing tasks with various variables, but the most important - id's of users signed to task (as different roles inside the task - author, graphic, corrector):
+---------+-------------+--------------+
| task_id | task_author | task_graphic |
+---------+-------------+--------------+
| 444 | 1 | 2 |
+---------+-------------+--------------+
Table users
+---------+----------------+------------+-----------+
| user_id | user_nice_name | user_login | user_role |
+---------+----------------+------------+-----------+
| 1 | Nice Name #1 | login1 | 0 |
+---------+----------------+------------+-----------+
| 2 | Bad Name #2 | login2 | 1 |
+---------+----------------+------------+-----------+
Using PDO I'm getting the whole data I want while using INNER JOIN with data from different tables (and $_GET variable)
SELECT tasks.*, types.types_name, warehouse.warehouse_id, warehouse.warehouse_code, warehouse.warehouse_description
FROM tasks
INNER JOIN types ON types.types_id = tasks.task_id
INNER JOIN warehouse ON warehouse.warehouse_id = tasks.task_id
WHERE tasks.task_id = '".$get_id."'
ORDER BY tasks.task_id
Above query returns:
+---------+--------------+--------------+----------------+------------+-----------+------------------+------------------------+------------+-------------+-----------------+-----------+----------------+--------------------+---------------------+-----------+---------------------+------------------+---------------------+
| task_id | task_creator | task_graphic | task_purchaser | task_title | task_lang | task_description | task_description_files | task_files | task_status | task_prod_index | task_type | task_print_run | task_print_company | task_warehouse_code | task_cost | task_time_added | task_deadline | task_date_warehouse |
+---------+--------------+--------------+----------------+------------+-----------+------------------+------------------------+------------+-------------+-----------------+-----------+----------------+--------------------+---------------------+-----------+---------------------+------------------+---------------------+
| 2 | 1 | 2 | 1 | Test | PL | Lorem ipsum (?) | | | w | 2222 | 3 | 456546 | Firma XYZ | 2 | 124 | 29.09.2016 15:48:20 | 01.10.2016 12:00 | 07.10.2016 14:00 |
+---------+--------------+--------------+----------------+------------+-----------+------------------+------------------------+------------+-------------+-----------------+-----------+----------------+--------------------+---------------------+-----------+---------------------+------------------+---------------------+
And I'd like to get query with added user_nice_name after task_creator, task_author and task_graphic - obviously nice names selected from table users based on ID's provide in 3 above fields fe.
+---------+--------------+------------------------------------+--------------+--------------------------------------+
| task_id | task_creator | task_creator_nn | task_graphic | task_graphic |
+---------+--------------+------------------------------------+--------------+--------------------------------------+
| 2 | 1 | Nice Name (from task_creator ID=1) | 2 | Nice Name (from task_graphic ID = 2) |
+---------+--------------+------------------------------------+--------------+--------------------------------------+
How can I achieve that?
You need three joins:
SELECT t.*,
uc.user_nice_name as creator_name,
ug.user_nice_name as graphic_name,
up.user_nice_name as purchaser_name,
ty.types_name, w.warehouse_id, w.warehouse_code, w.warehouse_description
FROM tasks t INNER JOIN
types ty
ON ty.types_id = t.task_id INNER JOIN
warehouse w
ON w.warehouse_id = t.task_id LEFT JOIN
users uc
ON uc.user_id = t.task_creator LEFT JOIN
users ug
ON ug.user_id = t.task_graphic LEFT JOIN
users up
ON up.user_id = t.task_purchaser
WHERE t.task_id = '".$get_id."'
ORDER BY t.task_id;
Notes:
Table aliases make the query easier to write and to read. They are also required because you have three references to users in the FROM clause.
This uses LEFT JOIN for the users in case some of the reference values are missing.
You need to work on your naming. It doesn't make sense that a "warehouse" id matches a "task" id. Or that a "task" id matches a "types" id. But that is how you phrased the query in your question.
The ORDER BY effectively does nothing, because all rows have the same task_id.
Assuming that the task_graphic_name is inside a table name task_graphic_table and the relation field are task_graphic_id
SELECT tasks.*
, types.types_name
, warehouse.warehouse_id
, warehouse.warehouse_code
, warehouse.warehouse_description
, users.user_nice_name
FROM tasks
INNER JOIN types ON types.types_id = tasks.task_id
INNER JOIN warehouse ON warehouse.warehouse_id = tasks.task_id
INNER JOIN users ON users.user_nice_name = tasks.task_graphic
WHERE tasks.task_id = '".$get_id."'
ORDER BY tasks.task_id
And if you need the column appear in a specific order you should explicitally call the column name in sequence eg:
SELECT tasks.col1
, task.col2
, types.types_name
, warehouse.warehouse_id
, warehouse.warehouse_code
, task.col2
, warehouse.warehouse_description
, task_graphic_table.task_graphic_name
Add two sub query in with your query. like
SELECT tasks.*,
....
....,
(select user_nice_name from users where id = tasks.task_author) AS task_creator_name,
(select user_nice_name from users where id = tasks.task_graphic) AS task_graphic_name
FROM tasks
INNER JOIN types ON types.types_id = tasks.task_id
....
....

mysql query to get all reviews for every company

I have a database with tables like below:
Reviews
id | review | companyid
companies
id | name
Now i want to get the data back so that i can show each company name with the total number of reviews for the company. Like seen below:
company 1 (company name) | 345
company 2 (company name) | 28
company 3 (company name) | 794
From here i will make a table using php to display the results
How can i achieve this with MYSQl?
Try this way:
SELECT Count(`r`.`review`) AS `total_reviews`,
`c`.`company`
FROM `reviews` AS `r`
JOIN `companies` AS `c`
ON `c`.`id` = `r`.`companyid`
Use COUNT and GROUP BY to count the reviews per company and use JOIN to get the company name from the other table.
Query
select t2.name as companyName,coalesce(t1.`count`,0) as `count` from
(
select companyid,count(companyid) as `count`
from reviews
group by companyid
)t1
right join companies t2
on t1.companyid= t2.id;
Sample Output
Table - reviews
+----+--------+-----------+
| id | review | companyid |
+----+--------+-----------+
| 1 | r1 | 1 |
| 2 | r2 | 2 |
| 3 | r3 | 1 |
+----+--------+-----------+
Table - companies
+----+------+
| id | name |
+----+------+
| 1 | C1 |
| 2 | C2 |
| 3 | C3 |
+----+------+
Output
+------+-------+
| name | count |
+------+-------+
| C1 | 2 |
| C2 | 1 |
| C3 | 0 |
+------+-------+
SQL Fiddle
You need to use a GROUP BY
SELECT r.companyid, c.name, count(r.id) as nb_review
FROM reviews r
INNER JOIN companies c ON (r.companyid = c.id)
GROUP BY r.companyid, c.name;
If you also want to see the companies with no reviews, do :
SELECT c.id, c.name, count(r.id) as nb_review
FROM companies c
LEFT JOIN reviews r ON (r.companyid = c.id)
GROUP BY c.id, c.name;

how do i select data from multiple columns from two tables where there is a common column in both?

seems like a cake walk, because of the common column thing, but i've looked and i've looked and can't find the answer anywhere. there may be very similar things people are trying to do, but everyone always needs it slightly different than how i need it. anyway here goes...
jobs table
+----+--------+----+----+----+
| id | userid | i1 | i2 | i3 |
+----+--------+----+----+----+
| 1 | 1 | a | k | t |
| 2 | 1 | b | l | u |
| 3 | 1 | c | m | v |
| 4 | 2 | d | n | w |
| 5 | 2 | f | o | x |
| 6 | 2 | g | p | y |
| 7 | 3 | h | q | z |
| 8 | 3 | i | r | a |
| 9 | 4 | j | s | b |
+----+--------+----+----+----+
user_table table
+--------+----+----+----+
| userid | fn | ln | i4 |
+--------+----+----+----+
| 1 | a | b | w |
| 2 | c | d | x |
| 3 | e | f | y |
| 4 | g | h | z |
+--------+----+----+----+
i want to select multiple columns from one table and multiple columns from another table, and the amount of columns don't have the same amount. so if i'm selecting id, i1, i2, and i3 from jobs table and selecting fn, ln, and i4 from user_table table, then that means i'm selecting 4 pieces of info from jobs table and 3 pieces of info from user_table table.
so let's say i want to select a specific job and display the info for that job, but also i want to display the info of the user that belongs to the job then it might go something like this...
job 1:
id: 1, i1: a, i2: k, i3: t, fn: a, ln: b, i4: w
for job 4 it would be:
id: 4, i1: d, i2: n, i3: w, fn: c, ln: d, i4: x
the jobs table and user_table table have the common column of userid. so how do i write my query to do the above using this common column?
i tried all sorts of things with SELECT and WHERE and AND and JOIN and UNION and AS and GROUP and BY and writing the table names separate from the column names and writing the table names and column names together with a period in between. i just can't find the correct way to write this query.
in these examples below that don't work i'm just trying to select one thing from the user_table table and everything from the jobs table that isn't the userid, but i will need the ability to select multiple things from the 2nd table if needed. so i want to select everything from first table and just certain things from second table.
doesn't work:
SELECT id, i1, i2, i3, i4 FROM jobs, user_table WHERE jobs.id = $id GROUP BY id
doesn't work:
SELECT * from jobs where id = $id UNION SELECT i4 from user_table where userid = $userid
The query
SELECT * FROM jobs
INNER JOIN user_table on jobs.userid = user_table.userid
will join your jobs information with the user information. Then just add your where clause:
SELECT * FROM jobs
INNER JOIN user_table on jobs.userid = user_table.userid
where jobs.id = $id
You want to join the tables like so:
SELECT j.column1, j.column2, u.column5, u.column6
FROM
jobs j
INNER JOIN
user_table u
ON
u.userid = j.userid
WHERE
j.id = $id
try
SELECT id, i1, i2, i3, i4 FROM jobs
inner join user_table on jobs.id = user_table.id WHERE jobs.id = $id GROUP BY id

Categories