display data together from 2 different SQL table - php

I need to display details from 2 different tables
Table 1- user table
Table 2-bicycle table
I can show a list of users and bicycle.
But can't show a list that show which bicycle belongs to who.
Bicycle table,
user table

You need to use a LEFT JOIN. The query below will connect your user table to your bicycle table based on the userIDand return all of the bicycle and user fields
SELECT b.*, u.*
FROM registered_users u
LEFT JOIN registered_bicycle b ON (u.userID = b.userID)
If you want specific bicycle fields just prefix them with b. Example:
SELECT b.brand, b.model, b.color...

Click on SQL tab and type this:
SELECT * FROM `registered_bicycle` JOIN `registered_users` ON `registered_users`.`userID` = `registered_bicycle`.`userID`
and run it

You have to make a foreign key from user_table to bicycle_table like this.
user_table has user_id = user_1,name=John Richard
bicycle_table has user_id = user_1,description = Bicycle1
to fetch the data:
select a.user_id, a.name,b.description from
(select user_id, name from user_table) as a
left join
(select user_id,description from bicycle_table) as b
on a.user_id = b.user_id

Related

joining 2 tables in msqli

table posts
table users
how would i count posts for specific user logged in. for example when user with id 3 is logged in it should show me 4 posts
I already did it for total posts count:
<?php
$post_query1 = "SELECT count(*) AS total FROM posts ";
$post_result1 = mysqli_query($db, $post_query1);
$post1 = mysqli_fetch_array($post_result1);
?>
Try below example :
select count(*) as total from user as u inner join post as p on p.id_user = u.id_user AND u.id_user = 3
If you want to get only the posts count for the particular user, say user with id = 3, your query should be this:
$query = "SELECT count(*) AS total FROM posts WHERE id_users = 3";
But if you want to get both the posts count as well as the user information and other post information, you will have to run a join query on both the users and posts table. Your query would now become:
$query = "SELECT u.*, p.*, count(p.id_posts) FROM users AS u JOIN posts AS p ON u.id_users = p.id_users WHERE p.id_users = 3";
Some Useful Notes
p.* - * is a wildcard character that means get all the columns in the posts table
u.* - * is a wildcard that means get all the columns in the users table
posts as p - AS is for aliasing. So, we are giving posts table a temporary name.
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
Note: It is necessary that you have to join two/more tables only with the help of foreign key. Without the foreign key is is meaningless to join two or more tables
Reference 1: https://www.w3schools.com/sql/sql_join.asp
Reference 2: https://www.tutorialspoint.com/mysql/mysql-using-joins.htm
As per the Question what you have asked to join the tables
Query:
SELECT * FROM TABLE 1 JOIN TABLE 2 ON TABLE1.id = TABLE2.id WHERE TABLE2.ID=3
Kindly replace TABLE1 & TABLE2 with the Tables that are to be joined and the id with the foreign key what you have specified in the Table.
Hope so this might be helpful for you to write your own code in future. Happy Coding :)
You have only to use a simple join.
SELECT count(*)
FROM USER u,
post p
WHERE p.id_user = u.id_user
AND u.id_user = 3

How to replace two user id columns with names?

I have a table with two columns.
created_by | assigned_to
One is the person who create a "to do card", the other column is the person who is assigned to do it.
The columns are filled with id, for example; (1,2,3).
My question is how can i replace this id with the names that are saved in another table.
by far this is what i got.
SELECT tickets.*, users.Name, users.LastName
FROM tickets
LEFT JOIN users ON tickets.assigned_to = users.uid
AND tickets.id_usuario = users.uid
but when i try to print the name of the persona
Created by: <?= query['Name']; ?>
Assigned to: <?= query['Name']; ?>
but i got the same name in both columns.
Your current query only joins to users when the creator and assigned-to user ID are the same.
You'll need to join to your users table twice to retrieve the separate records. You do this by adding more joins...
SELECT
c_users.Name as created_by_name,
c_users.LastName as created_by_last_name,
a_users.Name as assigned_to_name,
a_users.LastName as assigned_to_last_name
FROM tickets t
INNER JOIN users c_users
ON t.created_by = c_users.uid
-- or t.id_usuario = c_users.uid, it is not clear from your question
INNER JOIN users a_users
ON t.assigned_to = a_users.uid
I've used INNER JOIN instead of LEFT JOIN as it doesn't seem feasible that you'd have broken relationships between the two tables.

How to JOIN 2 tables on mySql?

I have two tables: publick_feed and users
I want to SELECT all from public_feed and also SELECT a three columns from users whose id is the same of user_id in public_feed
and assign the rows returned from public_feed to the column in users table ( correspondent)
I try this:
<?php
$sql = "
SELECT * FROM public_feed
WHERE user_id IN
(SELECT id FROM users) AND
(SELECT Firstname,Lastname,Avatar FROM users WHERE id IN(SELECT user_id FROM public_feed))
";
$query = mysqli_query($dbc_conn,$sql);
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_assoc($query)){
//echo rows with correspondent details from the users table
echo $row['user_id'];
}
}
<?
Please any help will be much appreciated.
Thank you.
Or version with left join in case if there is no user in public_feed, and you still want to fetch user data
SELECT
u.*, f.*
FROM
public_feed f LEFT JOIN
users u ON f.user_id = u.id;
Because author asked for explanation, here it is:
First we are going to use table name alias to make query shorter
public_feed f
and
users u
we are saying that want to refer to tables with an alias. Of course * means that we want to select all columns
SELECT users.*, public_feed.*
is equal to
SELECT u.*, f.*
Of course you can use any other letters as an alias
Next we are saying that public_feed.user_id must be equal to users.id. But when public feed entry does not exists just display columns with null values. This is why we are using LEFT JOIN instead of INNER JOIN. In general JOINS are used to fetch related data from more than one related tables.
ON keyword is saying values from which columns in the tables must be equal to satisfy the request
I think doing a join would be cleaner than using a complicated subquery:
SELECT u.Firstname,
u.Lastname,
u.Avatar,
COALESCE(pf.User_id, 'NA'),
COALESCE(pf.Post, 'NA'),
COALESCE(pf.Date, 'NA')
FROM users u
LEFT JOIN public_feed pf
ON u.Id = pf.User_id
I chose a LEFT JOIN of users against public_feed on the assumption that every feed will have an entry in the users table, but not necessarily vice-versa. For those users who have no feed entries, NA would appear in those columns and that user would appear in only a single record.

MYSQL - JOIN the 1 table or the other table depending if there is a match

I have a table called events and I am doing a select on this table to display a grid with the select results.
The events table has a column called s_code. The s_code value comes from either the suppliers or members table.
How would I do a single JOIN that checks the suppliers and members table to get the code's name without having to do a LEFT JOIN on both members and suppliers tables like my query below. Basically I only want to have b.s_name where I have both b.s_name and c.s_name at the moment.
SELECT a.s_id, b.s_name, c.s_name, a.s_date,
a.s_description, d.s_name, a.s_actiondate,
e.s_name, a.s_emailed, a.s_status
FROM events AS a
LEFT JOIN members AS b ON a.s_code = b.s_code
LEFT JOIN suppliers AS c ON a.s_code = c.s_code
LEFT JOIN webuser AS d ON a.s_userid = d.s_ai
LEFT JOIN webuser AS e ON a.s_actionuserid = e.s_ai
WHERE a.s_status = 'A'
AND a.s_userid = '1'
AND a.s_transactionstatus = 'A'
Just coalesce the two columns into one, if the first is non null return that, otherwise the second;
SELECT a.s_id, COALESCE(b.s_name, c.s_name) s_name, a.s_date, ...

MySQL, Find all employees of a "manager"

I have a "manager" that can be assigned to many locations and handles one department in every location. I want a query that can grab all of this:
http://sqlfiddle.com/#!2/33453c/1
In the example above (in the link) you can see I have calculated how many employees are in each department.
Managers and Employees are in a table named staff, I do not want the query to retrieve the manager record(s). So user_role = "Employee";
I run this as a raw query in laravel so I can retrieve them as objects:
$employees= DB::query('query goes in here')->get();
An example would be the manager with staff_id '5' get every employee that is in all of the locations and department the manager is part of if that makes sense?
My guess would be:
Pseudo
First Query SELECT ALL FROM staff, locations and departments where user_role = "employee"
Second Query SELECT ALL FROM staff, locations and departments where manager id=5
Remove all results that do not satisfy the second query but join both queries together?
Help would be greatly appreciated.
I think this is what you want. Left join the manager's department on employee's departments, and get the count of "employee" staff members in each of those departments (even if 0)
Below, shown for manager #2 (you could eliminate the where clause and group by manager id and dept id if you want to see all managers)
SELECT dept.name AS dept, loc.address1 AS loc, emp.*
FROM staff AS mgr
INNER JOIN department_staff AS mgr_dept
ON mgr_dept.staff_id = mgr.staff_id
INNER JOIN departments AS dept
ON mgr_dept.dept_id = dept.dept_id
INNER JOIN location_staff AS mgr_loc
ON mgr_loc.staff_id = mgr.staff_id
INNER JOIN locations AS loc
ON mgr_loc.loc_id = loc.loc_id
INNER JOIN (
SELECT emp.*, dept.dept_id, loc.loc_id
FROM staff AS emp
INNER JOIN department_staff AS dept
ON emp.staff_id = dept.staff_id
INNER JOIN location_staff AS loc
ON emp.staff_id = loc.staff_id
WHERE emp.user_role = "Employee"
) AS emp
ON emp.loc_id = mgr_loc.loc_id
AND emp.dept_id = mgr_dept.dept_id
WHERE mgr.staff_id = 2

Categories